1.人脸识别准备
使用的两个opencv包
powershell
D:\python2023>pip list |findstr opencv
opencv-contrib-python 4.8.1.78
opencv-python 4.8.1.78
数据集使用前一篇Javacv的数据集,网上随便找的60张图片,只是都挪到了D:\face目录下方便遍历
D:\face\1 30张刘德华图片
D:\face\2 30张刘亦菲图片
2.人脸识别模型训练
python
# -*- coding: utf-8 -*-
import os
import cv2
import numpy as np
recognizer = cv2.face.LBPHFaceRecognizer().create() # Fisher需要reshape
classifier = cv2.CascadeClassifier('E:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
def load_dataset(dataset_path):
images=[]
labels=[]
for root,dirs,files in os.walk(dataset_path):
for file in files:
images.append(cv2.imread(os.path.join(root, file),cv2.IMREAD_GRAYSCALE))
labels.append(int(os.path.basename(root)))
return images,labels
if __name__ == '__main__':
images,labels = load_dataset('D:\\face')
recognizer.train(images,np.array(labels))
recognizer.save('face_model.xml')
3.人脸识别推理预测
python
# -*- coding: utf-8 -*-
import os
import cv2
def face_detect(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
classifier = cv2.CascadeClassifier('E:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
faces = classifier.detectMultiScale(gray, 1.2, 5)
if (len(faces) == 0):
return None, None
(x, y, w, h) = faces[0]
return gray[y:y + w, x:x + h], faces[0]
def draw_rectangle(img, rect):
(x, y, w, h) = rect
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
def draw_text(img, text, x, y):
cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
def predict(image):
image_copy = image.copy()
face, rect = face_detect(image_copy)
tuple = recognizer.predict(face)
print(tuple)
draw_rectangle(image_copy, rect)
draw_text(image_copy, str(tuple[0]), rect[0], rect[1])
return image_copy
if __name__ == '__main__':
recognizer = cv2.face.LBPHFaceRecognizer().create() # Fisher需要reshape
recognizer.read("face_model.xml")
for root, dirs, files in os.walk('D:\\face\\2'):
for file in files:
file_path = os.path.join(root, file)
predict_image = predict(cv2.imread(file_path))
cv2.imshow('result', predict_image)
cv2.waitKey(1000)
总结
代码逻辑基本同Javacv,但更简洁,这里训练出来模型准确度也高于Javacv (可能是参数不一致导致的)