Python三十行程式碼實現簡單臉部辨識

2021-03-25 12:00:11

Python三十行程式碼實現簡單臉部辨識

一、庫介紹

opencv,face_recognition,numpy,以及dlib
注意:
安裝opencv速度可能過慢,需要更換國內映象源,參考:https://blog.csdn.net/X_xs_mxt/article/details/107069379
附帶Python3.7,64位元版本 dlib whl下載路徑:
連結:https://pan.baidu.com/s/1jOmwQ2OpJcbyYPSMisIFlg
提取碼:to50

二、庫安裝

pip install opencv-python
pip install face_recognition
pip install numpy

dlib庫需進入whl檔案路徑下安裝

pip install dlib-19.17.99-cp37-cp37m-win_amd64.whl

三、face_recognition庫簡單介紹

face_recognition的load_image_file方法會載入圖片,並返回一個ndarray型別的資料

face_path = "C://Users//25103//Desktop//Python臉部辨識//face//徐先生.jpg"
image = face_recognition.load_image_file(face_path)

face_recognition的face_encoding方法,可從返回的ndarray型別資料中提取人臉特徵,可同時提取多個特徵,返回值為列表型別

face_encoding = face_recognition.face_encodings(image)[0]

face_recognition的face_location方法可以獲取圖片中所有人臉的位置,其返回值為一個列表

face_locations = face_recognition.face_locations(rgb_frame)

四、程式碼實現以及註釋講解

# coding = utf-8
import dlib
import cv2
import face_recognition
import os

# 建立視訊物件
video_capture = cv2.VideoCapture(0)

# 載入需要識別的人臉圖片(這張圖片需要僅有一張臉)
# face_recognition的load_image_file方法會載入圖片,並返回一個ndarray型別的資料
# ndarray型別就是NumPy的陣列型別,其中的元素型別可以一致也可以不一致
face_path = "C://Users//25103//Desktop//Python臉部辨識//face//徐先生.jpg"
image = face_recognition.load_image_file(face_path)

# face_recognition的face_encoding方法,可從返回的ndarray型別資料中提取人臉特徵,可同時提取多個特徵,返回值為列表型別
# 因為照片中只有一個人臉,所以我們取列表的第一個值
face_encoding = face_recognition.face_encodings(image)[0]

while True:
    # 從視訊物件中讀取一幀照片
    ret,frame = video_capture.read()
    # 將照片縮小,加快處理速度,這裡將其縮小為原圖的1/4
    # frame = cv2.rectangle(frame,(0,0),fx=0.25,fy=0.25)
    # 因為cv2用的是BGR色彩,我們組要將其轉化為RGB進行處理
    rgb_frame = frame[:,:,::-1] # 列表轉置操作

    # face_recognition的face_location方法可以獲取圖片中所有人臉的位置,其返回值為一個列表
    face_locations = face_recognition.face_locations(rgb_frame)
    print("共從視訊中找到了{}張人臉".format(len(face_locations)))

    # 獲取視訊中所有人臉的特徵
    face_encodings = face_recognition.face_encodings(rgb_frame,face_locations)

    for face in face_encodings:
        # 比較兩個特徵值——encoding1與encoding2,匹配返回True,否則返回False。tolerance越低,顧名思義,容錯率越低,返回值為列表型別
        match = face_recognition.compare_faces([face_encoding],face,tolerance=0.4)
        name = "不認識的人"

        if match[0]:
            # face為圖片名稱
            name = os.path.basename(face_path[0:-4])
        print("找到了{}".format(name))