用Python实现一个简单的——人脸相似度对比
时间: 2023-10-27 15:04:34 浏览: 144
Python人脸相似度对比
好的,人脸相似度对比可以通过计算两张人脸图像的相似度来实现。在Python中,我们可以使用开源的人脸识别库dlib和OpenCV来实现。
具体步骤如下:
1. 安装dlib和OpenCV库,可以通过pip命令进行安装:
```
pip install dlib
pip install opencv-python
```
2. 加载需要对比的两张人脸图像,可以使用OpenCV的imread函数进行读取:
```
import cv2
img1 = cv2.imread("img1.jpg")
img2 = cv2.imread("img2.jpg")
```
3. 对图像进行预处理,使用dlib库中的人脸检测器和关键点检测器进行人脸对齐和裁剪:
```
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
def align_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
if len(rects) == 0:
return None
shape = predictor(gray, rects[0])
face_img = dlib.get_face_chip(img, shape, size=160)
return face_img
aligned_img1 = align_face(img1)
aligned_img2 = align_face(img2)
```
4. 使用OpenCV的ORB算法提取图像特征,并计算两张图像的相似度:
```
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(aligned_img1, None)
kp2, des2 = orb.detectAndCompute(aligned_img2, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
score = sum([match.distance for match in matches]) / len(matches)
```
这里使用了ORB算法和汉明距离作为相似度度量。score的值越小表示两张图像越相似。
完整代码如下:
```
import cv2
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
orb = cv2.ORB_create()
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
def align_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
if len(rects) == 0:
return None
shape = predictor(gray, rects[0])
face_img = dlib.get_face_chip(img, shape, size=160)
return face_img
def compare_faces(img1, img2):
aligned_img1 = align_face(img1)
aligned_img2 = align_face(img2)
if aligned_img1 is None or aligned_img2 is None:
return None
kp1, des1 = orb.detectAndCompute(aligned_img1, None)
kp2, des2 = orb.detectAndCompute(aligned_img2, None)
matches = bf.match(des1, des2)
score = sum([match.distance for match in matches]) / len(matches)
return score
img1 = cv2.imread("img1.jpg")
img2 = cv2.imread("img2.jpg")
score = compare_faces(img1, img2)
print("相似度:", score)
```
阅读全文