引语:本片文章介绍的是在树莓派上实现人脸识别的方案,具体涉及到的原理我在这篇文章中就不做过多解释了。
需要准备的材料(主要):树莓派3B+、罗技270i 电脑摄像头。
人脸识别流程 :
人脸检测,图像采集:
图1.1
模型训练:
图1.2
人脸识别:
图1.3
在写代码之前需要建立文件夹:
编写代码:需要将程序放在相应的文件夹下
take_photo.py
import cv2
import numpy as np
import os
#def generate_img("/home/pi/Public/face_recognize/date"):
face_cascade =cv2.CascadeClassifier('/home/pi/Public/face_recognize/haarcascade_frontalface_default.xml')
if (not os.path.isdir("/home/pi/Public/face_recognize/data/XiaoMing")):
os.makedirs("/home/pi/Public/face_recognize/data/Xiaoming")
cap = cv2.VideoCapture(0)
count = 0
while True:
ret,frame = cap.read()
x,y = frame.shape[0:2]
small_frame = cv2.resize(frame, (int(y/2), int(x/2)))
result = small_frame.copy()
gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
result = cv2.rectangle(result, (x, y), (x+w, y+h), (255, 0, 0), 2)
f = cv2.resize(gray[y:y+h, x:x+w], (200, 200))
if count<40:
cv2.imwrite("/home/pi/Public/face_recognize/data/XiaoMing/Xiaoming"+ '%s.pgm' % str(count), f)
print(count)
count+=1
cv2.imshow('face', result)
if cv2.waitKey(30) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
#if__name__=='__take_photo__':
#generate_img("/home/pi/Desktop/face_recognize/deta/Xiaoming")
face_recognize.py
import os
import sys
import cv2
import numpy as np
def read_images(path,sz=None):
c = 0
X, y = [], []
names = []
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 (filename == ".directory"):
continue
filepath = os.path.join(subject_path, filename)
im = cv2.imread(os.path.join(subject_path, filename),cv2.IMREAD_GRAYSCALE)
if (im is None):
print("image" + filepath + "is None")
if (sz is not None):
im = cv2.resize(im, sz)
X.append(np.asarray(im, dtype=np.uint8))
y.append(c)
except:
print("unexpected error")
raise
c = c+1
names.append(subdirname)
return [names, X, y]
read_dir = "/home/pi/Public/face_recognize/data"
[names, X, y] = read_images(read_dir)
y = np.asarray(y,dtype=np.int32)
model = cv2.face_EigenFaceRecognizer.create()
model.train(np.asarray(X), np.asarray(y))
face_cascade =cv2.CascadeClassifier('/home/pi/Public/face_recognize/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
x, y = frame.shape[0:2]
small_frame = cv2.resize(frame, (int(y/2), int(x/2)))
result = small_frame.copy()
gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
result = cv2.rectangle(result, (x,y), (x+w,y+h), (255, 0, 0), 2)
roi = gray[x:x+w,y:y+h]
try:
roi = cv2.resize(roi, (200,200), interpolation=cv2.INTER_LINEAR)
[p_label, p_confidence] = model.predict(roi)
#print(names[p_label])
cv2.putText(result, names[p_label], (x, y-20), cv2.FONT_HERSHEY_SIMPLEX,1, 255, 2)
except:
continue
cv2.imshow("recognize_face",result)
if cv2.waitKey(30)&0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
注意:这里用到了一个xml文件,需要的同学可以去搜索下载
然后运行我们的程序
将目录切换到程序所在目录,运行take_photo.py程序:
然后运行face_recognize.py程序