基于opencv的人脸识别 python 代码
时间: 2023-09-10 22:09:18 浏览: 176
以下是一段基于OpenCV的人脸识别的Python代码:
```python
import cv2
import numpy as np
# 加载已经训练好的人脸识别模型
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('ykc.yml')
# 加载人脸检测模型
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
def predict_faces(image_path):
# 读取图像并转为灰度图像
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 对检测到的每张人脸进行预测
for (x, y, w, h) in faces:
# 根据检测到的人脸区域提取出人脸
face_roi = gray\[y:y + h, x:x + w\]
# 进行人脸识别
label, confidence = recognizer.predict(face_roi)
# 在图像上绘制人脸区域和识别结果
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, f'Label: {label}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Face Recognition', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 调用函数进行人脸识别
image_path = 'test.jpg'
predict_faces(image_path)
```
这段代码首先加载已经训练好的人脸识别模型,并使用人脸检测模型对输入图像进行人脸检测。然后,对每一个检测到的人脸区域进行预测,并在图像上标注出人脸区域和识别结果。最后,显示结果图像。
请确保在运行代码之前,已经安装了OpenCV库,并将人脸检测模型(haarcascade_frontalface_alt2.xml)和训练好的人脸识别模型(ykc.yml)放置在相应的路径下。
#### 引用[.reference_title]
- *1* [基于OpenCv的人脸识别(Python完整代码)](https://blog.csdn.net/weixin_46291251/article/details/117996591?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168943661616800225519912%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168943661616800225519912&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1-117996591-null-null.article_score_rank&utm_term=%E5%9F%BA%E4%BA%8Eopencv%E7%9A%84%E4%BA%BA%E8%84%B8%E8%AF%86%E5%88%AB%20python%20%E4%BB%A3%E7%A0%81)[target="_blank"] [.reference_item]
- *2* [基于OpenCV-Python实现的人脸识别](https://blog.csdn.net/weixin_52978638/article/details/124287279?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168943661616800225519912%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168943661616800225519912&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-15-124287279-null-null.article_score_rank&utm_term=%E5%9F%BA%E4%BA%8Eopencv%E7%9A%84%E4%BA%BA%E8%84%B8%E8%AF%86%E5%88%AB%20python%20%E4%BB%A3%E7%A0%81)[target="_blank"] [.reference_item]
- *3* [opencv人脸识别(python)](https://blog.csdn.net/qq_52358027/article/details/126795333?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168943661616800225519912%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168943661616800225519912&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-12-126795333-null-null.article_score_rank&utm_term=%E5%9F%BA%E4%BA%8Eopencv%E7%9A%84%E4%BA%BA%E8%84%B8%E8%AF%86%E5%88%AB%20python%20%E4%BB%A3%E7%A0%81)[target="_blank"] [.reference_item]
[ .reference_list ]
阅读全文