教主的Python学习日志0x00:通过OpenCV和face_recognition实现摄像头人脸识别

教主的Python学习日志0x00:

通过OpenCV和face_recognition实现摄像头人脸识别

刚好这个学期学习Python,在尝试 微信自动回复脚本 失败后(tx把web微信给封了)
脑子一热,就想到了这个点子
说干就干,冲冲冲

准备工作:

要做固然是好事,可是意识到自己嘛也不会,于是开始面向搜索引擎编程
不查不知道,一查吓一跳
需要的工具居然有:

Python 2.7或者Python 3.3+(我用的是Python 3.6.1)
OpenCV库
face_recognition库

其中face_recognition库要是想在Windows上运行的话,还需要dlib库的支持

需要的工具就这些,还有一颗强大的心脏和能打字的双手
face_recognition库的安装教程:https://blog.csdn.net/weixin_40450867/article/details/81734815

OpenCV库的安装教程:https://www.jianshu.com/p/49a68d2f0b6a

在Python导入OpenCV库的教程:https://blog.csdn.net/qq_34186720/article/details/80425224

代码分析:

import face_recognition
import cv2
import numpy as np

# opencv是用于打开摄像头的,这句话当using namespace std写上就ok;
video_capture = cv2.VideoCapture(0)

# 此处的图片我用的是相对路径,也可以改用绝对路径
WCH_image = face_recognition.load_image_file("knownFace/WCH.jpg")
WCH_face_encoding = face_recognition.face_encodings(WCH_image)[0]

LYW_image = face_recognition.load_image_file("knownFace/LYW.jpg")
LYW_face_encoding = face_recognition.face_encodings(LYW_image)[0]

RZH_image = face_recognition.load_image_file("knownFace/RZH.jpg")
RZH_face_encoding = face_recognition.face_encodings(RZH_image)[0]

LJH_image = face_recognition.load_image_file("knownFace/LJH.jpg")
LJH_face_encoding = face_recognition.face_encodings(LJH_image)[0]

这个是我们的准备工作,建立一个图片数据库
要注意在 face_recognition.load_image_file()中的文件路径
可以是绝对路径如D:\Pycharm\Mine\faceRecognition\knownFace\WCH.jpg
也能是相对路径如knownFace/WCH.jpg
_ py文件在faceRecognition中_

# 建立一个列表来储存已知图片的128维编码
known_face_encodings = [
    WCH_face_encoding,
    LYW_face_encoding,
    RZH_face_encoding,
    LJH_face_encoding,    
]
# 建立一个列表来储存每个人的命名
known_face_names = [
    "WCH",
    "LYW",
    "RZH",
    "LJH",    
]
# 初始化
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

我写了,他能跑了,有什么好说的

while True:
	# 抓取其中一帧视频并将其分辨率缩小为1/4(为了更快)
    # 缩小到1/10能更快(但是精度更差)(屁话)
    ret, frame = video_capture.read()
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # 因为OpenCV用的是BGR颜色而face_Recognition用的是RGB所以需要转换
    rgb_small_frame = small_frame[:, :, ::-1]
    # 获取视频中所有面部并计数
    face_locations = face_recognition.face_locations(rgb_small_frame)
    num = len(face_locations)

    for i in range(0, num):

        if process_this_frame:
            # 将当前帧中所有面部编码
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

            face_names = []
            for face_encoding in face_encodings:
                # 判断当前人脸是否与已知库符合
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"

                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = np.argmin(face_distances)
                if matches[best_match_index]:
                    name = known_face_names[best_match_index]

                face_names.append(name)

        process_this_frame = not process_this_frame

这一段代码是对图像的处理
官方给出的样例中加快处理速度采用的就是缩小分辨率的办法
但是经过我的实际测试快不了多少
而且卡顿可以说有点厉害
这个原因暂时没弄明白,不知道为啥就是自己菜

        for (top, right, bottom, left), name in zip(face_locations, face_names):
            # 因为之前将分辨率缩小至 1/4 所以 因在此处放大
            top *= 4
            right *= 4
            bottom *= 4
            left *= 4

            # 脸周围画框 ,形同css语法
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)

            # 在框下面加上名字
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
            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

这一段接上面,是对截取到的图像进行处理并输出
我们做的处理包括 在识别到的人脸附件画框在框下标注此人的姓名
之后就是输出图像
由于我们设置的是一个while True的死循环,所以别忘了留一个退出的key
cv2.waitKey(1)就是这样一个跳板
他读取键盘缓冲区的按键码(有时候不止是ASCII码)
所以我们对其进行&0xFF,并与q的ASCII码比对,判断是否退出
cv2.waitKey(1) & 0xFF可以被等效替换为下面的代码

keycode = cv2.waitKey(1)
if keycode != -1:
	keycode &= 0xFF

之后关闭摄像头退出程序就好

说在后面:

这个程序还存在大量不足:

1.往库中添加新图片的时候代码修改不方便(没能实现动态添加)
2.程序运行速度实在是太太太太慢了(也不知道怎么改)
3.对儿童和亚裔的识别好像不是很准(据样例描述)

如果谁知道怎么解决的话拜托教教我!

参考资料:
face_recognition中文文档:https://www.jianshu.com/p/4dd131567015
face_recognition在Github:https://github.com/ageitgey/face_recognition/tree/master/examples

下面是一个基于PythonOpenCVface_recognition库的简单人脸识别代码示例: ```python import cv2 import face_recognition # 加载已知的人脸图像和对应的名字 obama_image = face_recognition.load_image_file("obama.jpg") obama_face_encoding = face_recognition.face_encodings(obama_image)[0] biden_image = face_recognition.load_image_file("biden.jpg") biden_face_encoding = face_recognition.face_encodings(biden_image)[0] known_face_encodings = [ obama_face_encoding, biden_face_encoding ] known_face_names = [ "Barack Obama", "Joe Biden" ] # 打开摄像头 cap = cv2.VideoCapture(0) while True: # 读取一帧图像 ret, frame = cap.read() # 转换为RGB图像 rgb_frame = frame[:, :, ::-1] # 检测人脸 face_locations = face_recognition.face_locations(rgb_frame) face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) # 遍历每个检测到的人脸 for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): # 判断是否和已知人脸匹配 matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" # 如果匹配到了已知人脸,则获取对应的名字 if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] # 在图像上绘制人脸矩形和名字 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) # 显示图像 cv2.imshow('Video', frame) # 按下q键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头和窗口资源 cap.release() cv2.destroyAllWindows() ``` 注意,这个代码示例需要在已经安装了face_recognition库和OpenCV库的Python环境中运行,还需要把`obama.jpg`和`biden.jpg`两个已知人脸图像放在代码所在目录下。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值