1. 程式人生 > >人工智慧之Python人臉識別技術,人人都能做識別!

人工智慧之Python人臉識別技術,人人都能做識別!

一、環境搭建

1.系統環境

Ubuntu 17.04
Python 2.7.14
pycharm 開發工具

2.開發環境,安裝各種系統包

  • 人臉檢測基於dlib,dlib依賴Boost和cmake
  • 在windows中如果要使用dlib還是比較麻煩的,如果想省時間可以在anaconda中安裝

conda install -c conda-forge dlib=19.4

$ sudo apt-get install build-essential cmake
$ sudo apt-get install libgtk-3-dev
$ sudo apt-get install libboost-all-dev
  • 其他重要的包
$ pip install numpy
$ pip install scipy
$ pip install opencv-python
$ pip install dlib
  • 安裝 face_recognition
# 安裝 face_recognition
$ pip install face_recognition
# 安裝face_recognition過程中會自動安裝 numpy、scipy 等 

加群:865597862可以獲取Python學習資料,和Python安裝教程已加上傳至群檔案,加群即可獲取!

二、使用教程

1、facial_features資料夾

此demo主要展示了識別指定圖片中人臉的特徵資料,下面就是人臉的八個特徵,我們就是要獲取特徵資料

        'chin',
        'left_eyebrow',
        'right_eyebrow',
        'nose_bridge',
        'nose_tip',
        'left_eye',
        'right_eye',
        'top_lip',
        'bottom_lip'

執行結果:

自動識別圖片中的人臉,並且識別它的特徵

原圖:

image

image

特徵資料,資料就是執行出來的矩陣,也就是一個二維陣列

image

程式碼:

# -*- coding: utf-8 -*-
# 自動識別人臉特徵
# filename : find_facial_features_in_picture.py

# 匯入pil模組 ,可用命令安裝 apt-get install python-Imaging
from PIL import Image, ImageDraw
# 匯入face_recogntion模組,可用命令安裝 pip install face_recognition
import face_recognition

# 將jpg檔案載入到numpy 陣列中
image = face_recognition.load_image_file("chenduling.jpg")

#查詢影象中所有面部的所有面部特徵
face_landmarks_list = face_recognition.face_landmarks(image)

print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))

for face_landmarks in face_landmarks_list:

   #列印此影象中每個面部特徵的位置
    facial_features = [
        'chin',
        'left_eyebrow',
        'right_eyebrow',
        'nose_bridge',
        'nose_tip',
        'left_eye',
        'right_eye',
        'top_lip',
        'bottom_lip'
    ]

    for facial_feature in facial_features:
        print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))

   #讓我們在影象中描繪出每個人臉特徵!
    pil_image = Image.fromarray(image)
    d = ImageDraw.Draw(pil_image)

    for facial_feature in facial_features:
        d.line(face_landmarks[facial_feature], width=5)

    pil_image.show() 

2、find_face資料夾

不僅能識別出來所有的人臉,而且可以將其截圖挨個顯示出來,列印在前臺視窗

原始的圖片

這裡寫圖片描述

識別的圖片

這裡寫圖片描述

程式碼:

# -*- coding: utf-8 -*-
#  識別圖片中的所有人臉並顯示出來
# filename : find_faces_in_picture.py

# 匯入pil模組 ,可用命令安裝 apt-get install python-Imaging
from PIL import Image
# 匯入face_recogntion模組,可用命令安裝 pip install face_recognition
import face_recognition

# 將jpg檔案載入到numpy 陣列中
image = face_recognition.load_image_file("yiqi.jpg")

# 使用預設的給予HOG模型查詢影象中所有人臉
# 這個方法已經相當準確了,但還是不如CNN模型那麼準確,因為沒有使用GPU加速
# 另請參見: find_faces_in_picture_cnn.py
face_locations = face_recognition.face_locations(image)

# 使用CNN模型
# face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn")

# 列印:我從圖片中找到了 多少 張人臉
print("I found {} face(s) in this photograph.".format(len(face_locations)))

# 迴圈找到的所有人臉
for face_location in face_locations:

        # 列印每張臉的位置資訊
        top, right, bottom, left = face_location
        print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right)) 
# 指定人臉的位置資訊,然後顯示人臉圖片
        face_image = image[top:bottom, left:right]
        pil_image = Image.fromarray(face_image)
        pil_image.show() 

3、know_face資料夾

通過設定的人臉圖片識別未知圖片中的人臉

# -*- coding: utf-8 -*-
# 識別人臉鑑定是哪個人

# 匯入face_recogntion模組,可用命令安裝 pip install face_recognition
import face_recognition

#將jpg檔案載入到numpy陣列中
chen_image = face_recognition.load_image_file("chenduling.jpg")
#要識別的圖片
unknown_image = face_recognition.load_image_file("sunyizheng.jpg")

#獲取每個影象檔案中每個面部的面部編碼
#由於每個影象中可能有多個面,所以返回一個編碼列表。
#但是由於我知道每個影象只有一個臉,我只關心每個影象中的第一個編碼,所以我取索引0。
chen_face_encoding = face_recognition.face_encodings(chen_image)[0]
print("chen_face_encoding:{}".format(chen_face_encoding))
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
print("unknown_face_encoding :{}".format(unknown_face_encoding))

known_faces = [
    chen_face_encoding
]
#結果是True/false的陣列,未知面孔known_faces陣列中的任何人相匹配的結果
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)

print("result :{}".format(results))
print("這個未知面孔是 陳都靈 嗎? {}".format(results[0]))
print("這個未知面孔是 我們從未見過的新面孔嗎? {}".format(not True in results)) 

4、video資料夾

通過呼叫電腦攝像頭動態獲取視訊內的人臉,將其和我們指定的圖片集進行匹配,可以告知我們視訊內的人臉是否是我們設定好的

實現:

image

程式碼:

# -*- coding: utf-8 -*-
# 攝像頭頭像識別
import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)

# 本地影象
chenduling_image = face_recognition.load_image_file("chenduling.jpg")
chenduling_face_encoding = face_recognition.face_encodings(chenduling_image)[0]

# 本地影象二
sunyizheng_image = face_recognition.load_image_file("sunyizheng.jpg")
sunyizheng_face_encoding = face_recognition.face_encodings(sunyizheng_image)[0]

# 本地圖片三
zhangzetian_image = face_recognition.load_image_file("zhangzetian.jpg")
zhangzetian_face_encoding = face_recognition.face_encodings(zhangzetian_image)[0]

# Create arrays of known face encodings and their names
# 臉部特徵資料的集合
known_face_encodings = [
    chenduling_face_encoding,
    sunyizheng_face_encoding,
    zhangzetian_face_encoding
]

# 人物名稱的集合
known_face_names = [
    "michong",
    "sunyizheng",
    "chenduling"
]

face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    # 讀取攝像頭畫面
    ret, frame = video_capture.read()

    # 改變攝像頭影象的大小,影象小,所做的計算就少
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # opencv的影象是BGR格式的,而我們需要是的RGB格式的,因此需要進行一個轉換。
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # 根據encoding來判斷是不是同一個人,是就輸出true,不是為flase
        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:
            # 預設為unknown
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # if match[0]:
            #     name = "michong"
            # 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)

        #加上標籤
        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
    cv2.imshow('monitor', frame)

    # 按Q退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

5、boss資料夾

本開源專案,主要是結合攝像頭程式+極光推送,實現識別攝像頭中的人臉。並且通過極光推送平臺給移動端傳送訊息!

小禮物