OpenCV python 人脸识别(分类)
人脸图片
资源图片:face.zip
import cv2
import numpy as np
def resize_img(path):
"""导入图片、调整图片尺寸至相同大小"""
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (250, 350))
return img
def main():
# 1.导入人脸训练图片
img_list = [resize_img("./face/a0.jpg"),
resize_img("./face/a1.jpg"),
resize_img("./face/a2.jpg"),
resize_img("./face/a3.jpg"),
resize_img("./face/b0.jpg"),
resize_img("./face/b1.jpg"),
resize_img("./face/b2.jpg"),
resize_img("./face/b3.jpg")]
# 2.设置图片标签类型
labels = [0, 0, 0, 0, 1, 1, 1, 1]
# 3.创建识别对象
# recognizer = cv2.face.EigenFaceRecognizer_create()
# recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer = cv2.face.FisherFaceRecognizer_create()
# 4.训练图片
recognizer.train(img_list, np.array(labels))
# 5.导入预测图片并预测
predict_image = resize_img("./face/b4.jpg")
label, confidence = recognizer.predict(predict_image)
# 6.显示预测结果
print("预测类型:", label)
print("置信度:", confidence)
if __name__ == '__main__':
main()
结果:
人脸识别 方法二
文件下载地址
链接: https://pan.baidu.com/s/1zgBEWllFIxrgazOIcl0csQ 提取码: 4cuc
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import numpy as np
import cv2 as cv
import sklearn.preprocessing as sp
# 哈尔级联分类器 人脸
fd = cv.CascadeClassifier('./haar/face.xml')
# 文件夹搜索图片
def search_faces(directory):
directory = os.path.normpath(directory)
faces = {}
for curdir, subdirs, files in os.walk(directory):
for jpeg in (file for file in files if file.endswith('.jpg')):
path = os.path.join(curdir, jpeg)
label = path.split(os.path.sep)[-2]
if label not in faces:
faces[label] = []
faces[label].append(path)
return faces
# 读取 训练集人脸 路径
train_faces = search_faces('./faces/training')
# 人名标签编码
codec = sp.LabelEncoder()
codec.fit(list(train_faces.keys()))
# 训练集 人脸检测并截取人脸
train_x, train_y = [], []
for label, filenames in train_faces.items():
for filename in filenames:
image = cv.imread(filename)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
faces = fd.detectMultiScale(gray, 1.1, 2, minSize=(100, 100))
for l, t, w, h in faces:
train_x.append(gray[t:t + h, l:l + w])
train_y.append(codec.transform([label])[0])
train_y = np.array(train_y)
# 创建模型 局部二值模式直方图人脸识别分类器
model = cv.face.LBPHFaceRecognizer_create()
model.train(train_x, train_y)
# 测试集 读取整理
test_faces = search_faces('./faces/testing')
test_x, test_y, test_z = [], [], []
for label, filenames in test_faces.items():
for filename in filenames:
image = cv.imread(filename)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
faces = fd.detectMultiScale(gray, 1.1, 2, minSize=(100, 100))
for l, t, w, h in faces:
test_x.append(gray[t:t + h, l:l + w])
test_y.append(codec.transform([label])[0])
a, b = int(w / 2), int(h / 2)
cv.ellipse(image, (l + a, t + b), (a, b), 0, 0, 360, (255, 0, 255), 2)
test_z.append(image)
test_y = np.array(test_y)
# 测试集预测
pred_test_y = []
for face in test_x:
pred_code = model.predict(face)[0]
pred_test_y.append(pred_code)
# 循环显示 预测结果对比
escape = False
while not escape:
for code, pred_code, image in zip(
test_y, pred_test_y, test_z):
label, pred_label = \
codec.inverse_transform([code, pred_code])
text = 'Label:{} {} {}(Predict)'.format(label,
'==' if code == pred_code else '!=',
pred_label)
cv.putText(image, text, (10, 60), cv.FONT_HERSHEY_SIMPLEX, 2,
(255, 255, 255), 6)
cv.imshow('Recognizing...', image)
if cv.waitKey(1000) == 27:
escape = True
cv.imwrite("faces.jpg", image)
break