上一讲,我给大家介绍了基本开发环境的搭建以及一些常见的必坑指南。这一篇我准备给大家上上干货。我们首先来进行一个人脸识别的准确率较低的代码进行讲解,让大家对人脸识别的原理以及编程步骤有一个初始化的了解,并且可以一目了然发现程序的不足。
import face_recognition
import cv2
video_capture = cv2.VideoCapture(1)
# VideoCapture打开摄像头,0为笔记本内置摄像头,1为外USB摄像头,或写入视频路径
mayun_img = face_recognition.load_image_file("lixing.jpg")
jobs_img = face_recognition.load_image_file("sunbiao.jpg")
mayun_face_encoding = face_recognition.face_encodings(mayun_img)[0]
jobs_face_encoding = face_recognition.face_encodings(jobs_img)[0]
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
ret, frame = video_capture.read()
# video_capture.read()按帧读取视频,ret,frame是获video_capture.read()方法的两个返回值。
# 其中ret是布尔值,如果读取帧是正确的则返回True,
# 如果文件读取到结尾,它的返回值就为False。frame就是每一帧的图像,是个三维矩阵。
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# 对截取到的图像进行处理
if process_this_frame:
face_locations = face_recognition.face_locations(small_frame)
face_encodings = face_recognition.face_encodings(small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
match = face_recognition.compare_faces([mayun_face_encoding, jobs_face_encoding], face_encoding)
if match[0]:
name = "lixing"
elif match[1]:
name = "sunbiao"
else:
name = "unknown"
print(name)
face_names.append(name)
process_this_frame = not process_this_frame
for (top, right, bottom, left), name in zip(face_locations, face_names):
top *= 4
right *= 4
bottom *= 4
left *= 4
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), 2)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left+6, bottom-6), font, 1.0, (255, 255, 255), 1)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
这段代码在网上很多地方都可以找到,希望各位小白能读懂他,并且可以根据自己的实际情况进行修改,前提是Import那两个库不会出错!
通过编译以及测试本段代码,可以发现人脸识别的精度并不是想象的那么高,不是为什么呢?难道代码当中就不存在可以提高精度的函数吗?第三方库当中没有这样的函数吗?
不要幼稚了,老外做东西还是很严谨的!预知详情,请听下回分解!
注意,这段代码只是可以玩玩而已,千万不能当真哟!
希望大家可以通过这段代码,掌握开启摄像头,摄像头截图,人脸识别预处理,第三方库应用函数基本入门.