30行以内的Python代码实现人脸识别与关键点检测
时间: 2024-10-03 07:01:02 浏览: 27
在Python中,我们可以使用开源库如OpenCV和dlib来进行人脸识别和关键点检测。下面是一个简单的30行左右的示例,它展示了如何使用dlib库的`face_recognition`模块来识别人脸并提取关键点:
```python
import cv2
from dlib import get_frontal_face_detector, facerec, landmark_predictor
# 下载预训练的人脸识别模型和关键点预测模型(首次运行需要)
detector = get_frontal_face_detector()
predictor = landmark_predictor("shape_predictor_68_face_landmarks.dat")
def detect_faces(image_path):
img = cv2.imread(image_path)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(gray_img)
for face in faces:
# 提取特征并匹配人脸
face_rect = dlib.rectangle(*face)
landmarks = predictor(gray_img, face_rect)
# 画出关键点
for n, point in enumerate(landmarks.parts()):
cv2.circle(img, (point.x, point.y), 2, (0, 255, 0), -1)
cv2.putText(img, str(n), (point.x - 10, point.y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return img
# 使用方法
image = detect_faces("path_to_your_image.jpg")
cv2.imshow("Face Detection and Keypoints", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文