本代码仅以像素对比。以人脸特征对比,可以使用face_recognition开源库,参考https://blog.51cto.com/u_16175447/11246241
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 加载人脸识别模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def detect_face(image_path):
# 读取图像
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
if len(faces) == 0:
print("没有检测到人脸")
return None
# 提取人脸区域
(x, y, w, h) = faces[0] # 只取第一张人脸
face = img[y:y + h, x:x + w]
return face
def compare_faces(face1, face2):
# 将两个脸部图像调整为相同的大小
face1 = cv2.resize(face1, (100, 100))
face2 = cv2.resize(face2, (100, 100))
# 计算差异
difference = cv2.absdiff(face1, face2)
result = np.sum(difference)
# 根据差异值给出结果
return result
# 主程序
if __name__ == "__main__":
# 加载两张待对比的图片
file1 = 'face_shenteng2.jpg'
file2 = 'face_shenteng.jpg'
face1 = detect_face(file1)
face2 = detect_face(file2)
# 展示原图
plt.subplot(2, 2, 1)
plt.title('Face1')
# plt.title('Face3')
plt.imshow(cv2.cvtColor(cv2.imread(file1), cv2.COLOR_BGR2RGB))
plt.subplot(2, 2, 2)
plt.title('Face2')
# plt.title('Face4')
plt.imshow(cv2.cvtColor(cv2.imread(file2), cv2.COLOR_BGR2RGB))
# 展示人脸
plt.subplot(2, 2, 3)
plt.imshow(cv2.cvtColor(face1, cv2.COLOR_BGR2RGB))
plt.subplot(2, 2, 4)
plt.imshow(cv2.cvtColor(face2, cv2.COLOR_BGR2RGB))
plt.show()
if face1 is not None and face2 is not None:
result_diff = compare_faces(face1, face2)
print(f'两张人脸的对比结果差异值: {result_diff}')
if result_diff < 100000: # 可以根据需要调整阈值
print("人脸匹配")
else:
print("人脸不匹配")
haarcascade_frontalface_default.xml可以从 GitHub数据文件夹 下载。
运行结果
两张人脸的对比结果差异值: 1769757
人脸不匹配