30分钟做一个人脸识别案例

1 篇文章 0 订阅
1 篇文章 0 订阅

文章基于face_recognition+OpenCV(大佬们真的是厉害,膜拜)

总结一下经验,以及遇到的坑

参考:

https://github.com/ageitgey/face_recognition/blob/master/README_Simplified_Chinese.md

https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py

https://gist.github.com/ageitgey/629d75c1baac34dfa5ca2a1928a7aeaf

Face Recognition

在Git hub上看到一个强大的开源项目:face_recognition,具体内容大家可以参考这里:

https://github.com/ageitgey/face_recognition/blob/master/README_Simplified_Chinese.md

环境配置:

官方推荐是

  • Python 3.3+ or Python 2.7
  • macOS or Linux
  • Windows并不是我们官方支持的,但也许也能用

1. 安装face_recognition 

      在安装face_recognition之前先要安装dlib和相关Python依赖,安装dlib之前又要安装cmake(有点绕。。。)

      cmake安装:

      先去官网下载自己对应的版本:Download | CMake

      下载完后安装,之后打开软件,在工具栏找到 Tools > How to install for command line use

       软件会向你展示几种安装方法,我选的是:

sudo "/Applications/CMake.app/Contents/bin/cmake-gui" --install

       在终端里输入该命令就ok了;

       dlib安装:(参考https://gist.github.com/ageitgey/629d75c1baac34dfa5ca2a1928a7aeaf

git clone https://github.com/davisking/dlib.git

       依次输入下面代码 

cd dlib
mkdir build
cd build
cmake ..
cmake --build .

安装完成以后,就可以进行face_recognition的安装了

pip3 install face_recognition

2. 验证安装是否成功

这里我们用一段代码来测试,新建一个文件夹img,在img下新建两个文件夹,分别命名为know和unknow

然后去搜集一些面部素材,这里我用的是Taylor Swfit和Tim Cook的,将收集到的素材放入know文件,并命名为对应的名字(为了简明易懂),konw文件下的文件是用来告诉机器这是谁,是让机器用来学习的。

unknow文件下放一些测试图片,这个文件下电脑不知道这是谁,需要电脑去判断

将文件放到根目录,在终端输入:

face_recognition img/know img/unknow

会输出类似内容

img/unknow/anne.jpeg,unknown_person
img/unknow/TS.jpeg,taylorSwift
img/unknow/xlz.jpeg,unknown_person
img/unknow/TM.jpg,timCook
img/unknow/Zuckerberg.jpeg,unknown_person

unknow_person代表没识别出的人,也就是在know文件中没有的人

有名字的是识别出来的,是与know文件里相对应的人

这样就表示我们安装成功了,下面进行实时的人脸识别。

3. 实时人脸检测

代码源自:https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py

安装cv2,也就是opencv

pip install opencv-python

安装numpy库

pip install numpy

然后新建文件: face_recog.py

基本上就是复制这里的代码

import face_recognition
import cv2
import numpy as np

# This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the
# other example, but it includes some basic performance tweaks to make things run a lot faster:
#   1. Process each video frame at 1/4 resolution (though still display it at full resolution)
#   2. Only detect faces in every other frame of video.

# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.

# Get a reference to webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)

# Load a sample picture and learn how to recognize it.
timCook_image = face_recognition.load_image_file("face_cv2/img/know/timCook.jpg")
timCook_face_encoding = face_recognition.face_encodings(timCook_image)[0]

# Load a second sample picture and learn how to recognize it.
taylor_image = face_recognition.load_image_file("face_cv2/img/know/taylorSwift.jpeg")
taylor_face_encoding = face_recognition.face_encodings(taylor_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    timCook_face_encoding,
    taylor_face_encoding
]
known_face_names = [
    "TimCook",
    "TaylorSwift"
]

# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        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:
            # See if the face is a match for the known face(s)
            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]

            # Or instead, use the known face with the smallest distance to the new face
            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


    # Display the results
    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

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face
        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)

    # Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()

在终端运行命令:(在调用摄像头这一部分,这里我出了点状况,在sublime text3中执行程序,会崩溃,但是在终端执行就没有问题,可能是我配置的有问题) 

python3 face_recog.py

如果成功启动程序,可以用手机搜几张Taylor或者Tim的图片对着摄像头测试。

       (图片来源:https://github.com/ageitgey/face_recognition/blob/master/README_Simplified_Chinese.md)

或者直接在know中存入你自己的照片,并修改这这一部分代码:

video_capture = cv2.VideoCapture(0)

# 加载第一个样本照片
timCook_image = face_recognition.load_image_file("face_cv2/img/know/timCook.jpg")
timCook_face_encoding = face_recognition.face_encodings(timCook_image)[0]

# 加载第二个样本照片
taylor_image = face_recognition.load_image_file("face_cv2/img/know/taylorSwift.jpeg")
taylor_face_encoding = face_recognition.face_encodings(taylor_image)[0]

# 加载你自己的照片
your_image = face_recognition.load_image_file("face_cv2/img/know/your.jpg")
your_face_encoding = face_recognition.face_encodings(your_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    timCook_face_encoding,
    taylor_face_encoding,
    your_face_encoding
]
known_face_names = [
    "TimCook",
    "TaylorSwift",
    "yourName"
]

退出程序按“q”建

 有讲的不明白的地方,或者出错的地方,大家可以私信我或者留言评论,一起学习一起进步。

  文章若有侵权,请及时联系我删除更改。

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值