问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Opencv学习02--人脸识别技术实战:5种常用方法详解与代码实现

创作时间:
作者:
@小白创作中心

Opencv学习02--人脸识别技术实战:5种常用方法详解与代码实现

引用
CSDN
1.
https://blog.csdn.net/2401_83372039/article/details/146637519

人脸识别是计算机视觉领域的核心技术之一,广泛应用于安防、支付、社交等领域。本文将介绍五种常用的人脸检测方法,并提供基于Python和OpenCV的代码实现,帮助读者快速上手实践。

一、Haar Cascade(哈尔级联检测器)

原理简介
Haar Cascade基于Haar-like特征和Adaboost分类器,通过级联结构快速筛选出人脸区域。优点是速度快,适合实时检测。

import cv2
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
plt.rcParams['figure.dpi']=200

# 读取图片
img = cv2.imread('path_to_your_image.jpg')
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show(block=True)

构建haar检测器以后:

# 构建haar检测器
face_detector = cv2.CascadeClassifier('path_to_haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
detection = face_detector.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=6, minSize=(30, 30), maxSize=(200, 200))
for (x, y, w, h) in detection:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()

二、HOG(方向梯度直方图)

原理简介
HOG通过计算图像的局部梯度方向直方图来描述特征,结合线性分类器实现检测。dlib库提供了高效的HOG人脸检测器。

img = cv2.imread('path_to_your_image.jpg')
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
import dlib
hog_face_detector = dlib.get_frontal_face_detector()
detection = hog_face_detector(img, 1)
for i in detection:
    start_point = (i.left(), i.top())
    end_point = (i.right(), i.bottom())
    cv2.rectangle(img, start_point, end_point, (255, 0, 0), 2)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show(block=True)

三、CNN(卷积神经网络)

原理简介
基于深度学习的CNN模型(如dlib的MMOD)通过卷积层提取高级特征,检测精度更高,但计算资源消耗较大。

import dlib
cnn_face_detector = dlib.cnn_face_detection_model_v1('path_to_mmod_human_face_detector.dat')
detection = cnn_face_detector(img, 1)
for i in detection:
    start_point = (i.rect.left(), i.rect.top())
    end_point = (i.rect.right(), i.rect.bottom())
    conf = i.confidence
    print(conf)
    cv2.rectangle(img, start_point, end_point, (255, 0, 0), 5)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

四、SSD(单阶段检测器)

原理简介
SSD(Single Shot MultiBox Detector)基于深度学习的端到端检测框架,兼顾速度与精度。OpenCV的DNN模块支持预训练模型。

detector = cv2.dnn.readNetFromCaffe('path_to_deploy.prototxt', 'path_to_res10_300x300_ssd_iter_140000.caffemodel')
img_height = img.shape[0]
img_width = img.shape[1]
img_resize = cv2.resize(img, (300, 300))
img_blob = cv2.dnn.blobFromImage(img_resize, 1.0, (300, 300), (104.0, 177.0, 123.0))
detector.setInput(img_blob)
detection = detector.forward()
for i in range(detection.shape[2]):
    confidence = detection[0, 0, i, 2]
    if confidence > 0.2:
        x1 = int(detection[0, 0, i, 3] * img_width)
        y1 = int(detection[0, 0, i, 4] * img_height)
        x2 = int(detection[0, 0, i, 5] * img_width)
        y2 = int(detection[0, 0, i, 6] * img_height)
        cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show(block=True)

五、MTCNN(多任务级联网络)

原理简介
MTCNN通过三个级联网络(P-Net、R-Net、O-Net)同时检测人脸和关键点,精度高但速度较慢。

from mtcnn.mtcnn import MTCNN
detector = MTCNN()
detection = detector.detect_faces(img)
for i in detection:
    start_point = (i['box'][0], i['box'][1])
    end_point = (i['box'][0]+i['box'][2], i['box'][1]+i['box'][3])
    cv2.rectangle(img, start_point, end_point, (255, 0, 0), 2)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show(block=True)

六、实时摄像头检测示例(Haar)

import cv2
cap = cv2.VideoCapture(0)
haar_face_detector = cv2.CascadeClassifier('path_to_haarcascade_frontalface_default.xml')
while True:
    ret, frame = cap.read()
    frame = cv2.flip(frame, 1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = haar_face_detector.detectMultiScale(gray, 1.2, 6)
    for x, y, w, h in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3)
    cv2.imshow('window', frame)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

方法对比与选型建议

方法
速度
精度
适用场景
Haar
★★★★
★★
实时检测、嵌入式设备
HOG
★★★
★★★
中等精度需求场景
CNN
★★
★★★★
高精度静态图像检测
SSD
★★★
★★★★
平衡速度与精度的场景
MTCNN
★★★★★
需要关键点的复杂场景

环境配置注意事项

  1. 安装依赖库:

    pip install opencv-python dlib mtcnn matplotlib tensorflow
    
  2. 模型文件需从官方渠道下载并正确配置路径。

  3. 实时检测需确保摄像头权限开启。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号