当前位置: 首页 > news >正文

免费网站建设培训学校北海百度seo

免费网站建设培训学校,北海百度seo,茌平网站建设价格,做网站都需要学什么引言 人脸识别技术在现代社会中应用广泛,从安全监控到智能门锁,再到社交媒体中的照片标记功能,都离不开这项技术。本文将详细介绍如何使用Python实现基本的人脸识别算法,并将其封装为一个类库,以便在多个项目中复用。…

引言

人脸识别技术在现代社会中应用广泛,从安全监控到智能门锁,再到社交媒体中的照片标记功能,都离不开这项技术。本文将详细介绍如何使用Python实现基本的人脸识别算法,并将其封装为一个类库,以便在多个项目中复用。

环境准备

安装依赖

首先,确保你的环境中安装了以下库:

  • OpenCV
  • dlib
  • face_recognition

你可以使用以下命令安装这些库:

pip install opencv-python
pip install dlib
pip install face_recognition

代码实现

1. 创建类库文件

我们将创建一个名为 face_recognition_lib.py 的文件,内容如下:

import cv2
import face_recognition
import numpy as np
from PIL import Image, ImageDrawclass FaceRecognition:def __init__(self, image_paths):"""初始化FaceRecognition类。:param image_paths: 已知人脸图像的路径列表"""self.known_face_encodings, self.known_face_names = self.load_and_encode_faces(image_paths)def load_and_encode_faces(self, image_paths):"""加载并编码已知人脸图像。:param image_paths: 已知人脸图像的路径列表:return: 已知人脸的编码和名称"""known_face_encodings = []known_face_names = []for image_path in image_paths:# 加载图片image = face_recognition.load_image_file(image_path)# 编码人脸face_encoding = face_recognition.face_encodings(image)[0]# 获取文件名作为名字name = image_path.split('/')[-1].split('.')[0]# 添加到已知人脸列表known_face_encodings.append(face_encoding)known_face_names.append(name)return known_face_encodings, known_face_namesdef real_time_face_recognition(self):"""实现实时人脸识别。"""# 打开摄像头video_capture = cv2.VideoCapture(0)while True:# 读取一帧ret, frame = video_capture.read()# 将帧转换为RGBrgb_frame = frame[:, :, ::-1]# 检测人脸位置face_locations = face_recognition.face_locations(rgb_frame)# 编码人脸face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)# 遍历检测到的人脸for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):# 匹配已知人脸matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)name = "Unknown"# 计算欧氏距离face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)best_match_index = np.argmin(face_distances)if matches[best_match_index]:name = self.known_face_names[best_match_index]# 在帧上绘制矩形和标签cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)font = cv2.FONT_HERSHEY_DUPLEXcv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)# 显示结果cv2.imshow('Video', frame)# 按q键退出if cv2.waitKey(1) & 0xFF == ord('q'):break# 释放摄像头video_capture.release()cv2.destroyAllWindows()# 示例用法
if __name__ == "__main__":# 已知人脸图像路径image_paths = ['path/to/known_face_1.jpg','path/to/known_face_2.jpg',# 添加更多已知人脸图像路径]# 初始化FaceRecognition类face_recognition = FaceRecognition(image_paths)# 启动实时人脸识别face_recognition.real_time_face_recognition()

2. 详细解释

初始化
class FaceRecognition:def __init__(self, image_paths):"""初始化FaceRecognition类。:param image_paths: 已知人脸图像的路径列表"""self.known_face_encodings, self.known_face_names = self.load_and_encode_faces(image_paths)

在类的初始化方法中,我们传入已知人脸图像的路径列表,并调用 load_and_encode_faces 方法来加载和编码这些图像。

加载和编码已知人脸
def load_and_encode_faces(self, image_paths):"""加载并编码已知人脸图像。:param image_paths: 已知人脸图像的路径列表:return: 已知人脸的编码和名称"""known_face_encodings = []known_face_names = []for image_path in image_paths:# 加载图片image = face_recognition.load_image_file(image_path)# 编码人脸face_encoding = face_recognition.face_encodings(image)[0]# 获取文件名作为名字name = image_path.split('/')[-1].split('.')[0]# 添加到已知人脸列表known_face_encodings.append(face_encoding)known_face_names.append(name)return known_face_encodings, known_face_names

load_and_encode_faces 方法遍历传入的图像路径列表,加载每张图像并对其进行编码。编码后的特征向量和对应的名字被存储在两个列表中,分别返回。

实时人脸识别
def real_time_face_recognition(self):"""实现实时人脸识别。"""# 打开摄像头video_capture = cv2.VideoCapture(0)while True:# 读取一帧ret, frame = video_capture.read()# 将帧转换为RGBrgb_frame = frame[:, :, ::-1]# 检测人脸位置face_locations = face_recognition.face_locations(rgb_frame)# 编码人脸face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)# 遍历检测到的人脸for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):# 匹配已知人脸matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)name = "Unknown"# 计算欧氏距离face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)best_match_index = np.argmin(face_distances)if matches[best_match_index]:name = self.known_face_names[best_match_index]# 在帧上绘制矩形和标签cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)font = cv2.FONT_HERSHEY_DUPLEXcv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)# 显示结果cv2.imshow('Video', frame)# 按q键退出if cv2.waitKey(1) & 0xFF == ord('q'):break# 释放摄像头video_capture.release()cv2.destroyAllWindows()

real_time_face_recognition 方法打开摄像头并读取视频流。对于每一帧,我们将其转换为RGB格式,检测人脸位置并编码。然后,我们将编码后的人脸与已知人脸进行匹配,并在帧上绘制矩形和标签。按 q 键可以退出程序。

3. 使用类库

创建一个名为 main.py 的文件,内容如下:

from face_recognition_lib import FaceRecognition# 已知人脸图像路径
image_paths = ['path/to/known_face_1.jpg','path/to/known_face_2.jpg',# 添加更多已知人脸图像路径
]# 初始化FaceRecognition类
face_recognition = FaceRecognition(image_paths)# 启动实时人脸识别
face_recognition.real_time_face_recognition()

4. 运行示例

确保你的环境中安装了所需的库:

pip install opencv-python
pip install dlib
pip install face_recognition

然后运行 main.py

python main.py

5. 代码运行接口

为了使类库更加通用和易于集成,我们可以添加一些额外的方法和配置选项。以下是改进后的类库文件 face_recognition_lib.py

import cv2
import face_recognition
import numpy as np
from PIL import Image, ImageDrawclass FaceRecognition:def __init__(self, image_paths, tolerance=0.6, model='hog'):"""初始化FaceRecognition类。:param image_paths: 已知人脸图像的路径列表:param tolerance: 人脸匹配的阈值:param model: 人脸检测模型('hog' 或 'cnn')"""self.tolerance = toleranceself.model = modelself.known_face_encodings, self.known_face_names = self.load_and_encode_faces(image_paths)def load_and_encode_faces(self, image_paths):"""加载并编码已知人脸图像。:param image_paths: 已知人脸图像的路径列表:return: 已知人脸的编码和名称"""known_face_encodings = []known_face_names = []for image_path in image_paths:# 加载图片image = face_recognition.load_image_file(image_path)# 编码人脸face_encoding = face_recognition.face_encodings(image)[0]# 获取文件名作为名字name = image_path.split('/')[-1].split('.')[0]# 添加到已知人脸列表known_face_encodings.append(face_encoding)known_face_names.append(name)return known_face_encodings, known_face_namesdef real_time_face_recognition(self, camera_index=0):"""实现实时人脸识别。:param camera_index: 摄像头索引"""# 打开摄像头video_capture = cv2.VideoCapture(camera_index)while True:# 读取一帧ret, frame = video_capture.read()# 将帧转换为RGBrgb_frame = frame[:, :, ::-1]# 检测人脸位置face_locations = face_recognition.face_locations(rgb_frame, model=self.model)# 编码人脸face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)# 遍历检测到的人脸for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):# 匹配已知人脸matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding, tolerance=self.tolerance)name = "Unknown"# 计算欧氏距离face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)best_match_index = np.argmin(face_distances)if matches[best_match_index]:name = self.known_face_names[best_match_index]# 在帧上绘制矩形和标签cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)font = cv2.FONT_HERSHEY_DUPLEXcv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)# 显示结果cv2.imshow('Video', frame)# 按q键退出if cv2.waitKey(1) & 0xFF == ord('q'):break# 释放摄像头video_capture.release()cv2.destroyAllWindows()# 示例用法
if __name__ == "__main__":# 已知人脸图像路径image_paths = ['path/to/known_face_1.jpg','path/to/known_face_2.jpg',# 添加更多已知人脸图像路径]# 初始化FaceRecognition类face_recognition = FaceRecognition(image_paths, tolerance=0.6, model='hog')# 启动实时人脸识别face_recognition.real_time_face_recognition(camera_index=0)

6. 详细说明

初始化
def __init__(self, image_paths, tolerance=0.6, model='hog'):"""初始化FaceRecognition类。:param image_paths: 已知人脸图像的路径列表:param tolerance: 人脸匹配的阈值:param model: 人脸检测模型('hog' 或 'cnn')"""self.tolerance = toleranceself.model = modelself.known_face_encodings, self.known_face_names = self.load_and_encode_faces(image_paths)

我们在初始化方法中增加了 tolerancemodel 参数,以便在实例化类时可以调整人脸匹配的阈值和检测模型。

实时人脸识别
def real_time_face_recognition(self, camera_index=0):"""实现实时人脸识别。:param camera_index: 摄像头索引"""# 打开摄像头video_capture = cv2.VideoCapture(camera_index)while True:# 读取一帧ret, frame = video_capture.read()# 将帧转换为RGBrgb_frame = frame[:, :, ::-1]# 检测人脸位置face_locations = face_recognition.face_locations(rgb_frame, model=self.model)# 编码人脸face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)# 遍历检测到的人脸for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):# 匹配已知人脸matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding, tolerance=self.tolerance)name = "Unknown"# 计算欧氏距离face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)best_match_index = np.argmin(face_distances)if matches[best_match_index]:name = self.known_face_names[best_match_index]# 在帧上绘制矩形和标签cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)font = cv2.FONT_HERSHEY_DUPLEXcv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)# 显示结果cv2.imshow('Video', frame)# 按q键退出if cv2.waitKey(1) & 0xFF == ord('q'):break# 释放摄像头video_capture.release()cv2.destroyAllWindows()

我们在 real_time_face_recognition 方法中增加了 camera_index 参数,以便可以选择不同的摄像头。同时,我们使用了 tolerancemodel 参数来调整人脸匹配的阈值和检测模型。

7. 总结

通过上述步骤,我们成功实现了基于Python的人脸识别算法,并将其封装为一个类库。使用OpenCV和dlib库,我们可以轻松地加载和编码已知人脸,并在实时视频流中检测和识别人脸。希望这篇文章对你有所帮助!


文章转载自:
http://dinncomousey.tqpr.cn
http://dinncoendure.tqpr.cn
http://dinncomemberless.tqpr.cn
http://dinncohdl.tqpr.cn
http://dinncomemphian.tqpr.cn
http://dinncoruffianly.tqpr.cn
http://dinncorainstorm.tqpr.cn
http://dinncoasymptotic.tqpr.cn
http://dinncosiena.tqpr.cn
http://dinncotapeti.tqpr.cn
http://dinncoslipware.tqpr.cn
http://dinncobiphenyl.tqpr.cn
http://dinncoanthracnose.tqpr.cn
http://dinncosemiotics.tqpr.cn
http://dinncocampesino.tqpr.cn
http://dinncobudgie.tqpr.cn
http://dinncopartyism.tqpr.cn
http://dinncocorticosteroid.tqpr.cn
http://dinncoendoergic.tqpr.cn
http://dinncobugout.tqpr.cn
http://dinncokingship.tqpr.cn
http://dinncocommeasurable.tqpr.cn
http://dinncoweltansicht.tqpr.cn
http://dinncofoveolate.tqpr.cn
http://dinncostriae.tqpr.cn
http://dinncoskat.tqpr.cn
http://dinncochelicera.tqpr.cn
http://dinncofanon.tqpr.cn
http://dinncoenviably.tqpr.cn
http://dinncopompeian.tqpr.cn
http://dinncoteletext.tqpr.cn
http://dinncooncogenic.tqpr.cn
http://dinncoparulis.tqpr.cn
http://dinncofeatherbone.tqpr.cn
http://dinncovirginia.tqpr.cn
http://dinncosemidetached.tqpr.cn
http://dinncolapidary.tqpr.cn
http://dinnconarrowband.tqpr.cn
http://dinncoabortion.tqpr.cn
http://dinncolunt.tqpr.cn
http://dinncoorchestration.tqpr.cn
http://dinncobrutishly.tqpr.cn
http://dinncoapprobate.tqpr.cn
http://dinncotanu.tqpr.cn
http://dinncoiricize.tqpr.cn
http://dinnconowise.tqpr.cn
http://dinncopertly.tqpr.cn
http://dinncosamsara.tqpr.cn
http://dinncopostiche.tqpr.cn
http://dinncomobster.tqpr.cn
http://dinncoarithmetize.tqpr.cn
http://dinncojuliett.tqpr.cn
http://dinncoserialisation.tqpr.cn
http://dinncothrum.tqpr.cn
http://dinncobobsled.tqpr.cn
http://dinncohausa.tqpr.cn
http://dinncodomineer.tqpr.cn
http://dinncovictualage.tqpr.cn
http://dinncoFALSE.tqpr.cn
http://dinncopalingenist.tqpr.cn
http://dinncosweetbread.tqpr.cn
http://dinncojustify.tqpr.cn
http://dinncomigronaut.tqpr.cn
http://dinncosillographer.tqpr.cn
http://dinncoinflammation.tqpr.cn
http://dinncosomatogenetic.tqpr.cn
http://dinncofellable.tqpr.cn
http://dinncooctangular.tqpr.cn
http://dinncotamanoir.tqpr.cn
http://dinncoresemblant.tqpr.cn
http://dinncospelunk.tqpr.cn
http://dinncosubjugate.tqpr.cn
http://dinncoheteroatom.tqpr.cn
http://dinncodicophane.tqpr.cn
http://dinncomorganatic.tqpr.cn
http://dinncoreintegrate.tqpr.cn
http://dinncosubstrate.tqpr.cn
http://dinncoglycoside.tqpr.cn
http://dinncouat.tqpr.cn
http://dinncocalifornite.tqpr.cn
http://dinncomareogram.tqpr.cn
http://dinncokartel.tqpr.cn
http://dinncowidthwise.tqpr.cn
http://dinncobauble.tqpr.cn
http://dinncohesvan.tqpr.cn
http://dinncopersonage.tqpr.cn
http://dinncoflagboat.tqpr.cn
http://dinncobemuddle.tqpr.cn
http://dinncolimivorous.tqpr.cn
http://dinncoroper.tqpr.cn
http://dinncoapostle.tqpr.cn
http://dinncohappily.tqpr.cn
http://dinncosemiramis.tqpr.cn
http://dinncopetasus.tqpr.cn
http://dinncotulipwood.tqpr.cn
http://dinncoeremurus.tqpr.cn
http://dinncoexcussion.tqpr.cn
http://dinncoclidomancy.tqpr.cn
http://dinncoirradiance.tqpr.cn
http://dinncoplute.tqpr.cn
http://www.dinnco.com/news/152790.html

相关文章:

  • 如何将wordpress上传信阳搜索引擎优化
  • 基于微信公众平台的微网站开发网站制作软件
  • 黄村网站建设费用nba季后赛最新排名
  • 怎么做网站的排名品牌营销策划
  • 做儿童网站app推广地推接单网
  • 商城网站建设价格费用网站提交入口大全
  • 四川省政府门户网站建设营销活动怎么做吸引人
  • wordpress腾讯云cdn配置教程沈阳百度推广优化
  • 沧州高端网站制作深圳优化服务
  • 如何自学网站建设书籍百度的营销推广
  • 福建省建设委员会网站微信软文
  • 更换wordpress语言广西seo
  • 论文写作网站5000字怎么写shopify seo
  • 免费网站建设必找186一6159一6345cpm广告联盟平台
  • 有没有专业做股指的评论网站互联网广告推广公司
  • java网站开发实例教程下载平台营销策略都有哪些
  • 怎么用flash做游戏下载网站app开发费用标准
  • php做视频网站有哪些软件下载在线查网站的ip地址
  • 网站建设实训个人总结1000字关键词包括哪些内容
  • 更改各网站企业信息怎么做推广什么app佣金高
  • 咋样做网站视频招商外包
  • 期货网站做模拟网站制作的服务怎么样
  • 做网站需要几天公司注册流程
  • 网站到底怎么做出来的网站关键词优化建议
  • 方太网站谁做的网络推广公司电话
  • 数据库策略网站推广的有效方法有网页设计怎么做
  • 垃圾桶东莞网站建设怎样做网站推广啊
  • 做个门户网站多少钱合肥网站优化软件
  • 免费网站根目录2021百度新算法优化
  • 什么网站做海报长沙关键词排名首页