python实现人脸检测比对
时间: 2023-12-04 08:41:14 浏览: 122
以下是使用dlib库实现人脸检测比对的Python代码:
```python
import dlib
import numpy as np
# 加载人脸检测器和68点模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 加载两张图片
img1 = dlib.load_rgb_image('img1.jpg')
img2 = dlib.load_rgb_image('img2.jpg')
# 检测人脸并获取特征点
def get_features(img):
dets = detector(img, 1)
if len(dets) == 0:
return None
face = max(dets, key=lambda d: d.area())
shape = predictor(img, face)
features = np.array([[p.x, p.y] for p in shape.parts()])
return features
# 获取两张图片的特征点
features1 = get_features(img1)
features2 = get_features(img2)
# 计算欧氏距离
def euclidean_distance(x, y):
return np.sqrt(np.sum((x - y) ** 2))
# 计算两张图片的人脸相似度
def face_similarity(img1, img2):
features1 = get_features(img1)
features2 = get_features(img2)
if features1 is None or features2 is None:
return None
dist = euclidean_distance(features1.mean(axis=0), features2.mean(axis=0))
return dist
# 输出两张图片的人脸相似度
similarity = face_similarity(img1, img2)
print('两张图片的人脸相似度为:', similarity)
```
阅读全文