参考博客:
1. OpenCV-Python 4.5.4 人脸识别应用:https://blog.csdn.net/qq_36563273/article/details/121510440( 代码就是在此博客代码基础上改的,主要添加了人脸画框的逻辑 )
1. windows环境:win11
2. 安装 miniconda2-4.7.10:
3. 新建 python3.9 的 conda 环境:
1. 创建 conda 环境并瞎下载 opencv、numpy:
conda create --name conda_env_python_3_9 python=3.9
conda activate conda_env_python_3_9
pip install opencv-python==4.5.4.58 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install numpy==1.22.4 -i https://pypi.tuna.tsinghua.edu.cn/simple
2. 查看安装情况:
4. test.py:
import cv2
# 定义输入和变量
img1 = cv2.imread('face_img/hezhao.jpeg')
img2 = cv2.imread('face_img/yaoming_02.jpeg')
new_shape = (300, 300) # 统一缩放为 300*300
cos_thresh = 0.363 # cos阈值,距离越大越接近
L2_thresh = 1.128 # L2阈值,距离越小越接近
img1 = cv2.resize(img1, new_shape)
img2 = cv2.resize(img2, new_shape)
# 初始化模型:
faceDetector = cv2.FaceDetectorYN.create('face_model/yunet.onnx', '', new_shape)
faceRecognizer = cv2.FaceRecognizerSF.create('face_model/face_recognizer_fast.onnx', '')
# 检测、对齐、提取特征:
# detect输出的是一个二维元祖,其中第二维是一个二维数组: n*15,n为人脸数,
# 15为人脸的xywh和5个关键点(右眼瞳孔、左眼、鼻尖、右嘴角、左嘴角)的xy坐标及置信度
faces1 = faceDetector.detect(img1)
face_count = len( faces1[1] )
print("人脸个数:")
print( face_count )
for i in range( 0,face_count ):
print( i )
face_key_info_array = faces1[1][ i ]
x1 = int( face_key_info_array[ 0 ] )
y1 = int( face_key_info_array[ 1 ] )
width = int( face_key_info_array[ 2 ] )
height = int( face_key_info_array[ 3 ] )
x2 = x1 + width
y2 = y1 + height
# 在图片上画矩形框
# cv2.rectangle(img1, (x1, y1), (x2, y2), color, thickness)
cv2.rectangle(img1, (x1,y1), (x2,y2), (0,255,0), 1, cv2.LINE_8)
print( )
cv2.imshow("image", img1)
cv2.waitKey(0)
aligned_face1 = faceRecognizer.alignCrop(img1, faces1[1][0]) # 对齐后的图片
feature1 = faceRecognizer.feature(aligned_face1); # 128维特征
# faces2 = faceDetector.detect(img2)
print( faces2 )
aligned_face2 = faceRecognizer.alignCrop(img2, faces2[1][0])
feature2 = faceRecognizer.feature(aligned_face2);
cv2.imwrite('face_img/aligned1.jpg',aligned_face1)
cv2.imwrite('face_img/aligned2.jpg',aligned_face2)
# 人脸匹配值打分:
cos_score = faceRecognizer.match(feature1, feature2, 0)
L2_score = faceRecognizer.match(feature1, feature2, 1)
5. 代码目录结构:
6. 运行展示效果: