Python3.6+OpenCV3.0人脸识别代码

0、建立项目文件夹

G:\Python_work\face_detect

在“face_detect”文件夹中建立“generate.py”、“check_image.py”、“face_recognition.py”文件

以及“data”、“cascades”文件夹;“cascades”文件夹中包含各类人脸检测的XML文件,如:“haarcascade_eye.xml”

“haarcascade_frontalface_default.xml”文件等;在“data”文件夹内建立“ChenXiaoHan”“WuLiJing”“YuTao”子文件夹(可依据人名自行设置);

1、生成人脸识别数据(代码)

import cv2
import os

path=r'G:\Python_work\face_detect\cascades'

def generate():
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_cascade.load(path+'\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
eye_cascade.load(path+'\haarcascade_eye.xml')
camera = cv2.VideoCapture(0)
count = 0
while(True):
ret,frame = camera.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in faces:
img = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
f=cv2.resize(gray[y:y+h,x:x+w],(200,200))
cv2.imwrite(r'.\data\YuTao\%s.pgm' % str(count),f)
count += 1

cv2.imshow("camera",frame)
if cv2.waitKey(1) & 0xff == ord("q"):
break
camera.release()
cv2.destroyAllWindows()

if __name__ == "__main__":

generate()


2、查看训练数据集(代码)

import cv2

img = cv2.imread(r"G:\Python_work\face_detect\data\YuTao\0.pgm",
cv2.IMREAD_GRAYSCALE)

print(img)

cv2.imshow('img',img)
cv2.waitKey()

cv2.destroyAllWindows()

3、人脸识别(代码)

import cv2
import os
import sys
import numpy as np

def read_images(path,sz=None):
c=0
X,y = [],[]
for dirname,dirnames,filenames in os.walk(path):
for subdirname in dirnames:
subject_path =  os.path.join(dirname,subdirname)
for filename in os.listdir(subject_path):
try:
if not filename.endswith('.pgm'):
continue
filepath = os.path.join(subject_path,filename)

im = cv2.imread(os.path.join(subject_path,filename),
cv2.IMREAD_GRAYSCALE)

if(sz is not None):
im = cv2.resize(im,(200,200))

X.append(np.asarray(im,dtype=np.uint8))
y.append(c)

except (IOError,(errno,strerror)):
print("I/O error({0}):{1}".format(errno,strerror))

except:
print("Unexcepted error:",sys.exc_info()[0])
raise
c=c+1

return[X,y]

def face_rec(img_path):
    names = ['ChenXiaoHan','WuLiJing','YuTao']
    [X,y] = read_images(img_path)
    y = np.asarray(y, dtype=np.int32)
    model = cv2.face.EigenFaceRecognizer_create()

    model.train(np.asarray(X), np.asarray(y))

    camera = cv2.VideoCapture(0)
    face_cascade = cv2.CascadeClassifier(
            r'G:\Python_work\face_detect\cascades\haarcascade_frontalface_default.xml')
    while (True):
        read, img = camera.read()
        faces = face_cascade.detectMultiScale(img, 1.3, 5)
        for (x, y, w, h) in faces:
            img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            roi = gray[x: x+w, y: y+h]
            try:
                roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR)
                params = model.predict(roi)
                print("Label: %s, Confidence: %.2f" % (params[0], params[1]))
                cv2.putText(img, names[params[0]], (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
            except:
                continue
        cv2.imshow("camera", img)
        if cv2.waitKey(1) & 0xff == ord('q'):
            break
    cv2.destroyAllWindows()

if __name__ == "__main__":
    face_rec(r'G:\Python_work\face_detect\data')

你可能感兴趣的:(Python3.6+OpenCV3.0人脸识别代码)