opencv实现简单人脸识别
对于opencv 它提供了许多已经练习好的模型可供使用,我们需要通过他们来进行人脸识别
参考了网上许多资料
假设你已经配好了开发环境 ,在我之前的博客中由开发环境的配置。
项目代码结构:
dataSet : 存储训练用的图片,他由data_gen生成,当然也可以修改代码由其他方式生成
haarcascade_frontalface_alt.xml 、 haarcascade_frontalface_default.xml: 用于人脸检测的haar分类器,网上普遍说第一个效果更好,第二个运行速度更快
data_gen.py:生成我们所需的数据
trainer.py: 训练数据集
train.yml: 由train.py生成的人脸识别模型,供后面的人脸识别使用
recognize.py:视频中的人脸识别
data_gen.py
连续拍20张照片当作训练数据,每个人建立一组数据
import cv2 detector = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') cap = cv2.VideoCapture(0) sampleNum = 0 Id = input('enter your id: ') while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = detector.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # incrementing sample number sampleNum = sampleNum + 1 # saving the captured face in the dataset folder cv2.imwrite("dataSet/User." + str(Id) + '.' + str(sampleNum) + ".jpg", gray[y:y + h, x:x + w]) # cv2.imshow('frame', img) # wait for 100 miliseconds if cv2.waitKey(100) & 0xFF == ord('q'): break # break if the sample number is morethan 20 elif sampleNum > 20: break cap.release() cv2.destroyAllWindows()
train.py
训练数据
import cv2 import os import numpy as np from PIL import Image # recognizer = cv2.createLBPHFaceRecognizer() detector = cv2.CascadeClassifier("/Users/qiuchenglin/PycharmProjects/face_recognize/haarcascade_frontalface_alt.xml") recognizer = cv2.face.LBPHFaceRecognizer_create() def get_images_and_labels(path): image_paths = [os.path.join(path, f) for f in os.listdir(path)] face_samples = [] ids = [] for image_path in image_paths: image = Image.open(image_path).convert('L') image_np = np.array(image, 'uint8') if os.path.split(image_path)[-1].split(".")[-1] != 'jpg': continue image_id = int(os.path.split(image_path)[-1].split(".")[1]) faces = detector.detectMultiScale(image_np) for (x, y, w, h) in faces: face_samples.append(image_np[y:y + h, x:x + w]) ids.append(image_id) return face_samples, ids Faces, Ids = get_images_and_labels('dataSet') recognizer.train(Faces, np.array(Ids)) recognizer.save('trainner.yml')
recognize.py
下面就是根据训练好的模型进行人脸识别,根据之前生成数据的编号,可以填入相对应的人名,例如以下示例我训练了三组人的数据
import cv2 import numpy as np recognizer = cv2.face.LBPHFaceRecognizer_create() # recognizer = cv2.createLBPHFaceRecognizer() # in OpenCV 2 recognizer.read('/Users/qiuchenglin/PycharmProjects/face_recognize/trainner.yml') # recognizer.load('trainner/trainner.yml') # in OpenCV 2 cascade_path = "/Users/qiuchenglin/PycharmProjects/face_recognize/haarcascade_frontalface_alt.xml" face_cascade = cv2.CascadeClassifier(cascade_path) cam = cv2.VideoCapture(0) # font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) # in OpenCV 2 font = cv2.FONT_HERSHEY_SIMPLEX while True: ret, im = cam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.2, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x - 50, y - 50), (x + w + 50, y + h + 50), (225, 0, 0), 2) img_id, conf = recognizer.predict(gray[y:y + h, x:x + w]) if conf > 50: if img_id == 1: img_id = 'liuzb' elif img_id == 2: img_id = 'linqc' elif img_id == 3: img_id = 'keaibao' else: img_id = "Unknown" # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255) cv2.putText(im, str(img_id), (x, y), font, 1, (0, 255, 0), 1) cv2.imshow('im', im) if cv2.waitKey(10) & 0xFF == ord('q'): break cam.release() cv2.destroyAllWindows()
简单的一个人脸识别就完成了,只能说准确率没有非常高。
之后想办法进行提高。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。