1 环境与安装

  • Mac10.13.2

  • python3

  • freetype

pip3 install freetype-py
  • opencv
pip3 install opencv-python
  • face_recognition
pip install face_recognition

2 实时测试代码

realtime_facerecognition.py

#-*-coding:utf-8-*-
import face_recognition
import cv2
import chinese

# 使用默认的摄像头0
video_capture = cv2.VideoCapture(0)

# 读取图片,提取特征
xdqlive_image = face_recognition.load_image_file("xdqlive.jpg")
xdqlive_face_encoding = face_recognition.face_encodings(xdqlive_image)[0]

# 创建人脸特征数组及名字
known_face_encodings = [
    xdqlive_face_encoding
]
known_face_names = [
    "测试模特"
]

# 初始化变量
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
	    # 从视频捕捉一帧画面
    ret, frame = video_capture.read()

    # 为加快处理速度,调节画面尺寸为原来的1/4
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # 颜色转换BGR转为RGB
    rgb_small_frame = small_frame[:, :, ::-1]

    # 为节约山,仅处理两张图片
    if process_this_frame:
        # 识别人脸并进行特征提取(单张、多张均可)
        face_locations = face_recognition.face_locations(rgb_small_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"

            # If a match was found in known_face_encodings, just use the first one.
            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_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):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # 绘制矩形框
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        ch  = chinese.put_chinese_text('msyh.ttf')
        # 绘制标题框
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        
        frame = ch.draw_text(frame,  (left + 10, bottom-26 ), name, 20, (255, 255, 255))

    # 显示结果
    cv2.imshow('Video', frame)

    # 输入q退出识别
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头
video_capture.release()
cv2.destroyAllWindows()

3 结果

实现人脸实时检测,并标注人脸中文姓名。(不上图了,代码可测,有问题请留言。)


[参考文献]
[1]https://github.com/ageitgey/face_recognition
[2]https://blog.csdn.net/Nirvana_6174/article/details/81411842


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐