这个问题是关于使用Python OpenCV进行人脸识别,无摄像头输入,有准备好的人脸照片文件夹,,给出python代码
时间: 2024-03-10 19:50:53 浏览: 56
当然可以,以下是基于OpenCV和LBPH算法的Python代码示例,用于从准备好的人脸照片文件夹中识别人脸:
```python
import cv2
import os
import numpy as np
# 准备好的人脸照片文件夹路径
face_folder_path = "path/to/faces/folder"
# LBPH算法参数
radius = 1
neighbors = 8
grid_x = 8
grid_y = 8
threshold = 100
# 初始化LBPH算法
recognizer = cv2.face.LBPHFaceRecognizer_create(radius, neighbors, grid_x, grid_y, threshold)
# 收集人脸数据和标签
faces = []
labels = []
for label, name in enumerate(os.listdir(face_folder_path)):
for file_name in os.listdir(os.path.join(face_folder_path, name)):
image_path = os.path.join(face_folder_path, name, file_name)
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
faces.append(image)
labels.append(label)
# 训练LBPH算法
recognizer.train(faces, np.array(labels))
# 加载待识别的图片,进行人脸检测和特征提取
test_image_path = "path/to/test/image"
test_image = cv2.imread(test_image_path, cv2.IMREAD_GRAYSCALE)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(test_image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 遍历检测到的人脸,进行识别
for (x, y, w, h) in faces:
roi = test_image[y:y+h, x:x+w]
label, confidence = recognizer.predict(roi)
# 显示识别结果
if confidence < threshold:
name = os.listdir(face_folder_path)[label]
else:
name = "unknown"
cv2.rectangle(test_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(test_image, name, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示识别结果
cv2.imshow("Face Recognition", test_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
您需要将`face_folder_path`和`test_image_path`替换成您自己的路径,并下载适用于您的OpenCV版本的Haar特征级联分类器(例如`haarcascade_frontalface_default.xml`),并将其与您的代码放在同一个目录中。
阅读全文