opencv—人脸识别、分类
程序员文章站
2024-03-02 18:48:16
...
备注:
‘’’
一.training-data 存放训练照片的文件夹
training-data/s1 放第一个人的照片各种表情状态是否佩戴眼镜等情况的照片
training-data/s2是放第二人的照片各种表情状态是否佩戴眼镜等情况的照片
以此类推
有多少人建多少个文件夹
二、test-data文件夹放置的是要识别人脸的照片
三、face_cascade :lbpcascade_frontalface.xml放置的路径
‘’’
代码1:
# coding: utf-8
import cv2
import os
import numpy as np
import shutil
import glob
subjects = ["a", "b","c","d","e"] #预测
def detect_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('../cv-class/lbpcascade_frontalface.xml') #opencv自带的分类器
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=1)
if (len(faces) == 0):
return None, None
(x, y, w, h) = faces[0]
return gray[y:y + w, x:x + h], faces[0]
def prepare_training_data(data_folder_path):
dirs = os.listdir(data_folder_path)
faces = []
labels = []
for dir_name in dirs:
if not dir_name.startswith("s"):
continue;
label = int(dir_name.replace("s", ""))
subject_dir_path = data_folder_path + "/" + dir_name
subject_images_names = os.listdir(subject_dir_path)
for image_name in subject_images_names:
if image_name.startswith("."):
continue;
image_path = subject_dir_path + "/" + image_name
image = cv2.imread(image_path)
cv2.imshow("Training on image...", cv2.resize(image, (400, 500)))
cv2.waitKey(100)
face, rect = detect_face(image)
if face is not None:
faces.append(face)
labels.append(label)
cv2.waitKey(1)
cv2.destroyAllWindows()
return faces, labels
print("Preparing data...")
faces, labels = prepare_training_data("training-data") #调用训练库
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))
face_recognizer = cv2.face.createLBPHFaceRecognizer()
face_recognizer.train(faces, np.array(labels)) #开始训练模型
def draw_rectangle(img, rect):
(x, y, w, h) = rect
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
def draw_text(img, text, x, y):
cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
def predict(test_img):
img = test_img.copy()
face, rect = detect_face(img)
label = face_recognizer.predict(face)
label_text = subjects[label-1]
if label_text == 'a':
print(label_text, '1')
shutil.copy(file,'img2/1/'+file.split('\\')[-1])
if label_text == 'b':
print(label_text, '2')
shutil.copy(file,'img2/2/'+file.split('\\')[-1])
if label_text == 'c':
print(label_text, '3')
shutil.copy(file, 'img2/3/' + file.split('\\')[-1])
if label_text == 'd':
print(label_text, '4')
shutil.copy(file, 'img2/4/' + file.split('\\')[-1])
if label_text == 'e':
print(label_text, '5')
shutil.copy(file, 'img2/5/' + file.split('\\')[-1])
draw_rectangle(img, rect)
draw_text(img, label_text, rect[0], rect[1] - 5)
return img
files = glob.glob('img/*.jpg')
for file in files:
print(file)
test_img = cv2.imread(file)
predicted_img = predict(test_img)
# cv2.imshow(subjects[1], cv2.resize(predicted_img, (400, 500)))
# cv2.waitKey(1)
# cv2.destroyAllWindows()
得到结果如下,分类正确:
省略剩下三个文件夹。
代码2—自己训练模型,进行识别人类:
# coding: utf-8
import cv2
import os
import numpy as np
import shutil
import glob
subjects = ["a", "b","c","d","e"] #预测
def detect_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('../cv-class/lbpcascade_frontalface.xml')
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=1)
if (len(faces) == 0):
return None, None
(x, y, w, h) = faces[0]
return gray[y:y + w, x:x + h], faces[0]
def prepare_training_data(data_folder_path):
dirs = os.listdir(data_folder_path)
faces = []
labels = []
for dir_name in dirs:
if not dir_name.startswith("s"):
continue;
label = int(dir_name.replace("s", ""))
subject_dir_path = data_folder_path + "/" + dir_name
subject_images_names = os.listdir(subject_dir_path)
for image_name in subject_images_names:
if image_name.startswith("."):
continue;
image_path = subject_dir_path + "/" + image_name
image = cv2.imread(image_path)
cv2.imshow("Training on image...", cv2.resize(image, (400, 500)))
cv2.waitKey(100)
face, rect = detect_face(image)
if face is not None:
faces.append(face)
labels.append(label)
cv2.waitKey(1)
cv2.destroyAllWindows()
return faces, labels
print("Preparing data...")
faces, labels = prepare_training_data("training-data") #调用训练库
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))
face_recognizer = cv2.face.createLBPHFaceRecognizer()
face_recognizer.train(faces, np.array(labels)) #开始训练模型
face_recognizer.save('training-data/trainner.yml')
上一篇: 31 多媒体文件操作简述