写一个人脸识别的python代码
时间: 2024-03-02 20:23:33 浏览: 23
以下是一个简单的 Python 人脸识别代码,需要使用 OpenCV 和 dlib 库:
``` python
import cv2
import dlib
# 加载模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 加载图像
img = cv2.imread('test.jpg')
# 图像灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = detector(gray)
# 遍历检测到的人脸
for face in faces:
# 获取人脸特征点
landmarks = predictor(gray, face)
# 绘制人脸框
cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 2)
# 绘制特征点
for i in range(68):
x = landmarks.part(i).x
y = landmarks.part(i).y
cv2.circle(img, (x, y), 2, (0, 0, 255), -1)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
需要注意的是,此代码只是对人脸进行了简单的检测和特征点绘制,如果需要进行更加复杂的人脸识别,可以使用其他的库或者算法。