赞
踩
人脸识别是一种技术,通过检测、跟踪和识别人脸上的关键特征,以确认人脸的身份。它通常用于安保系统、身份验证、社交媒体和人机交互等领域。
人脸识别技术的基本原理是先通过图像处理和计算机视觉算法,提取人脸的特征点和特征描述。然后将这些特征与事先录入的人脸数据库进行比对,以确定人脸的身份。
在人脸识别技术中,一般包含以下步骤:人脸检测、人脸对齐、特征提取和特征匹配。人脸检测是指在图像或视频中检测到人脸的位置;人脸对齐是为了使得人脸特征点在后续处理中更容易提取;特征提取是指将人脸图像转换为具有辨识度的特征向量;特征匹配是将提取出的特征与数据库中的特征进行比对。
目前人脸检测的方法主要有两大类:基于知识和基于统计。
人脸识别技术的应用非常广泛,包括但不限于身份识别、门禁系统、公安系统、智能手机解锁、相册分类、人机交互等。随着深度学习的快速发展,人脸识别技术的准确率和效果得到了显著提升,越来越多的领域开始应用这项技术。然而,人脸识别技术也涉及到一些隐私和安全问题,需要合理的使用和管理。
人脸识别在OpenCV上也有专门的算法实现,OpenCV使用基于Haar特征的级联分类器,对级联分类器进行特定的训练可以使OpenCV自带的检测器在检测时的结果更加准确。这里的检测器即OpenCV包中的haarcascades文件夹下的XML文件。这些文件可以检测静止的图像或摄像头中得到的人脸。
opencv中内置了已经训练好的级联人脸、眼睛、嘴部等检测器,以.XML格式存储,可以将它们应用于图片及实时视频流的检测。opencv的人脸检测级联检测器是最稳定和准确的,但在许多情况下眼睛检测和嘴巴检测的效果要差上许多。如果要对眼睛和嘴巴进行检测,可以尝试python、dlib、opencv工作流,它的效果更好、速度更快。
Haar级联算法是OpenCV最流行的目标检测算法,主要优点是速度快,尽管许多算法(如HOG+线性SVM、SSDs、更快的R-CNN、YOLO等等)比Haar级联算法更精确。但如果需要纯粹的速度,就是无法打败OpenCV的Haar cascades。Haar级联的缺点是容易出现假阳性检测,应用于推理/检测时需要进行参数调整。
haarcascade_frontalface_default.xml:检测面部
haarcascade_eye.xml:检测左眼和右眼
haarcascade_smile.xml:检测面部是否存在嘴部
haarcascade_eye_tree_eyeglasses.xml:检测是否带墨镜
haarcascade_frontalcatface.xml:检测猫脸
haarcascade_frontalcatface_extended.xml:检测猫脸延伸
haarcascade_frontalface_alt.xml:检测人脸属性
haarcascade_frontalface_alt_tree.xml
haarcascade_frontalface_alt2.xml
haarcascade_fullbody.xml:检测全身
haarcascade_lefteye_2splits.xml:检测左眼
haarcascade_licence_plate_rus_16stages.xml:检测证件
haarcascade_lowerbody.xml:检测下半身
haarcascade_profileface.xml
haarcascade_righteye_2splits.xml:检测右眼
haarcascade_russian_plate_number.xml:检测俄罗斯字母车牌号
haarcascade_upperbody.xml:检测上半身
- import cv2 as cv
-
- def StaticDetect(filename):
- """静态图像"""
- # 创建一个级联分类器 加载一个 .xml 分类器文件. 它既可以是Haar特征也可以是LBP特征的分类器.
- face_cascade = cv.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
-
- # 加载图像
- img = cv.imread(filename)
- # 转换为灰度图
- gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
- # 进行人脸检测,传入scaleFactor,minNeighbors,分别表示人脸检测过程中每次迭代时图像的压缩率以及
- # 每个人脸矩形保留近似数目的最小值
- # 返回人脸矩形数组
- faces = face_cascade.detectMultiScale(gray_img, 1.3, 5)
- for (x, y, w, h) in faces:
- # 在原图像上绘制矩形
- img = cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
- cv.namedWindow('Face Detected!')
- cv.imshow('Face Detected!', img)
-
- # 使程序停留,等待任意键按下,参数表示停留的时间,0表示无限长
- k = cv.waitKey(0)
-
- # 按下ESC键(ASCII码为27)后,销毁所有窗口,终止程序
- if k == 27:
- cv.destroyAllWindows()
-
-
- if __name__ == '__main__':
- filename = 'face.png'
- StaticDetect(filename)

单人和多人脸均可检测。
Mediapipe 由 Google Research 于 2020 年推出,旨在为计算机视觉研究人员和开发者提供一个易于使用、高性能的框架。Mediapipe 提供了多种预训练模型和算法,涵盖了人脸检测、手势识别、姿态估计等领域。
MediaPipe是用于构建多模态(例如视频、音频或任何时间序列数据)、跨平台(即eAndroid、IOS、web、边缘设备)应用ML管道的框架。
以上2个模块都可以实现人脸检测,经过在树莓派上的实验发现,使用MediaPipe较OpenCV速度快,本文将利用MediaPipe实现检测人脸功能,并将检测到的人脸图像保存下来。
本实验将检测到人脸信息,并将实时检测到的图像保存到image文件夹内,以时间戳命名,每秒一个文件。
- """
- Face Detection Module
- By: Computer Vision Zone
- Website: https://www.computervision.zone/
- """
-
- import cv2,os,time
- import mediapipe as mp
- from datetime import datetime
-
- class FaceDetector:
- """
- Find faces in realtime using the light weight model provided in the mediapipe
- library.
- """
-
- def __init__(self, minDetectionCon=0.5):
- """
- :param minDetectionCon: Minimum Detection Confidence Threshold
- """
-
- self.minDetectionCon = minDetectionCon
- self.mpFaceDetection = mp.solutions.face_detection
- self.mpDraw = mp.solutions.drawing_utils
- self.faceDetection = self.mpFaceDetection.FaceDetection(self.minDetectionCon)
-
- def findFaces(self, img, draw=True):
- """
- Find faces in an image and return the bbox info
- :param img: Image to find the faces in.
- :param draw: Flag to draw the output on the image.
- :return: Image with or without drawings.
- Bounding Box list.
- """
-
- imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
- self.results = self.faceDetection.process(imgRGB)
- bboxs = []
- if self.results.detections:
- for id, detection in enumerate(self.results.detections):
- bboxC = detection.location_data.relative_bounding_box
- ih, iw, ic = img.shape
- bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih), \
- int(bboxC.width * iw), int(bboxC.height * ih)
- cx, cy = bbox[0] + (bbox[2] // 2), \
- bbox[1] + (bbox[3] // 2)
- bboxInfo = {"id": id, "bbox": bbox, "score": detection.score, "center": (cx, cy)}
- bboxs.append(bboxInfo)
- if draw:
- img = cv2.rectangle(img, bbox, (255, 0, 255), 2)
-
- cv2.putText(img, f'{int(detection.score[0] * 100)}%',
- (bbox[0], bbox[1] - 20), cv2.FONT_HERSHEY_PLAIN,
- 2, (255, 0, 255), 2)
- return img, bboxs
-
-
- def Timestamp_Get():
- now = datetime.now()
- datetime_str = now.strftime('%Y-%m-%d %H:%M:%S').replace(':','-').replace(' ','_')
- datetime_str = datetime_str+'.jpg'
- return datetime_str
-
- def main():
- cap = cv2.VideoCapture(0)
- detector = FaceDetector()
- file_path='./image'
- while True:
- success, img = cap.read()
- img, bboxs = detector.findFaces(img)
- if bboxs:
- time.sleep(0.02)
- if bboxs:
- # bboxInfo - "id","bbox","score","center"
- center = bboxs[0]["center"]
- cv2.circle(img, center, 5, (255, 0, 255), cv2.FILLED)
- file_name = os.path.join(file_path,Timestamp_Get())
- cv2.imwrite(file_name,img)
- time.sleep(1)
- cv2.imshow("Image", img)
- if cv2.waitKey(20) == ord('q'):
- break
- cap.release()
- cv2.destroyAllWindows()
- elif cv2.waitKey(20) == ord('s'):
- time.sleep(1)
- file_name = os.path.join('./image',Timestamp_Get())
- cv2.imwrite(file_name,img)
- print(file_name+'保存成功')
- time.sleep(1)
-
-
-
-
- if __name__ == "__main__":
-
- main()

(1)人脸检测类FaceDetector的findFaces方法可以检测人脸在整个图像的位置,经试验,不光是人脸,人手也可以被检测。还有检测的概率,以及人脸的中心像素点的位置。
(2)Timestamp_Get,获取当前的时间戳,作为文件名保存。
file_name = os.path.join(file_path,Timestamp_Get()) cv2.imwrite(file_name,img)
(3)人脸检测的情况可能会出现误检、抖动的情况,我们通过得分和消抖来进行局部调整。
score的类型是google._upb._message.RepeatedScalarContainer,它
是 Protocol Buffers 中的一个内部类,用于表示重复的标量值(即,一个数组)。要将此容器转换为浮点数列表,再转成float
这样检测目标低于60%概率的人脸就不会被保存。
(4)该程序支持自动保存,也支持手动保存。
随便在手机上找个美女试试效果吧
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。