1. 程式人生 > 實用技巧 >用Python檢測人臉特徵

用Python檢測人臉特徵

作者|Juan Cruz Martinez
編譯|Flin
來源|towardsdatascience

今天,我們將學習如何檢測影象中的人臉並提取面部特徵,如眼睛、鼻子、嘴巴等。我們可以將這些資訊作為一個預處理步驟來完成,例如捕捉照片中人物的人臉(手動或通過機器學習),建立效果來“增強”我們的影象(類似於Snapchat等應用程式中的效果),對人臉進行情感分析等等。

過去,我們已經討論過如何使用OpenCV來檢測影象中的形狀,但是今天我們將通過引入DLib和從影象中提取面部特徵來將其提升到一個新的水平。

Dlib是一個高階的機器學習庫,它是為解決複雜的現實世界問題而建立的。這個庫是用C++程式語言建立的,它與C/C++、Python和java一起工作。

值得注意的是,本教程可能需要對OpenCV庫有一定的瞭解,例如如何處理影象、開啟相機、影象處理和一些小技巧。

它是如何工作的?

我們的臉有幾個可以識別的特徵,比如眼睛、嘴巴、鼻子等等。當我們使用DLib演算法檢測這些特徵時,我們實際上得到了每個特徵的點的對映。
該對映由67個點(稱為地標點)組成,可識別以下特徵:

  • 顎點= 0–16
  • 右眉點= 17–21
  • 左眉點= 22–26
  • 鼻點= 27–35
  • 右眼點= 36–41
  • 左眼點= 42–47
  • 口角= 48–60
  • 嘴脣分數= 61–67

現在讓我們來了解如何提取特徵。

安裝要求

與往常一樣,本文將用程式碼演示示例,並將逐步指導你實現一個完整的人臉特徵識別示例。但是在開始之前,你需要啟動一個新的Python專案並安裝3個不同的庫:

  • opencv python
  • dlib

如果像我一樣使用pipenv,可以使用以下命令安裝所有這些檔案:

pipenv install opencv-python, dlib

如果你使用的是Mac和某些版本的Linux,則在安裝dlib時可能會遇到一些問題,如果在安裝過程中遇到編譯錯誤,請確保檢查使用的CMake庫版本。在Mac中,確保你有可用的CMake,並且可以使用正確的版本執行:

brew install cmake

對於其他作業系統,請線上檢查以獲得特定支援。

步驟1:載入並顯示圖片

我們將從小處著手並以程式碼為基礎,直到有一個可以正常工作的示例為止。

通常,我喜歡使用繪圖來渲染影象,但是由於我們在稍後的文章中準備了一些很酷的東西,因此我們將做一些不同的事情,並且將建立一個視窗來展示我們的工作結果。

讓我們一起看看程式碼吧!

import cv2
# read the image
img = cv2.imread("face.jpg")
# show the image
cv2.imshow(winname="Face", mat=img)
# Wait for a key press to exit
cv2.waitKey(delay=0)
# Close all windows
cv2.destroyAllWindows()

很簡單,對吧?我們只是用imread載入影象,然後告訴OpenCV在winname中顯示影象,這將開啟視窗並給它一個標題。

之後,我們需要暫停執行,因為當指令碼停止時,視窗會被破壞,所以我們使用cv2.waitKey來保持視窗,直到按下某個鍵,然後銷燬視窗並退出指令碼。

如果使用程式碼並在程式碼目錄中添加了一個名為face.jpg的影象,你應該得到如下內容:

原始影象:

步驟2:人臉識別

到目前為止,我們還沒有對影象做任何處理,只是把它呈現在一個視窗中,非常無聊,但是現在我們將開始編碼好的內容,我們將從識別影象中哪裡有一張臉開始。

為此,我們將使用名為get_frontial_face_detector()的Dlib函式,非常直觀。但是有一個警告,這個函式只適用於灰度影象,所以我們必須首先使用OpenCV。

get_frontial_face_detector()將返回一個檢測器,該檢測器是一個我們可以用來檢索人臉資訊的函式。每個面都是一個物件,其中包含可以找到影象的點。

但我們最好在程式碼上看看:

import cv2
import dlib
# Load the detector
detector = dlib.get_frontal_face_detector()
# read the image
img = cv2.imread("face.jpg")
# Convert image into grayscale
gray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
# Use detector to find landmarks
faces = detector(gray)
for face in faces:
    x1 = face.left() # left point
    y1 = face.top() # top point
    x2 = face.right() # right point
    y2 = face.bottom() # bottom point
    # Draw a rectangle
    cv2.rectangle(img=img, pt1=(x1, y1), pt2=(x2, y2), color=(0, 255, 0), thickness=4)
# show the image
cv2.imshow(winname="Face", mat=img)
# Wait for a key press to exit
cv2.waitKey(delay=0)
# Close all windows
cv2.destroyAllWindows()

上面的程式碼將從影象中檢索所有面部,並在每個面部上渲染一個矩形,從而產生如下影象:

到目前為止,我們在發現人臉方面做得很好,但是我們仍然需要一些工作來提取所有特徵(地標)。接下來讓我們開始吧。

步驟3:識別人臉特徵

你喜歡魔術嗎?到目前為止,DLib的工作方式相當神奇,只需幾行程式碼我們就可以實現很多,而現在我們遇到了一個全新的問題,它還會繼續這麼簡單嗎?

回答是肯定的!原來DLib提供了一個名為shape_predictor()的函式,它將為我們提供所有的魔法,但是需要一個預先訓練的模型才能工作。

有幾種模型可以與shape_predictor一起工作,我正在使用的模型可以在這裡下載,也可以嘗試其他模型。

讓我們看看新程式碼現在是什麼樣子

import cv2
import dlib
# Load the detector
detector = dlib.get_frontal_face_detector()
# Load the predictor
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# read the image
img = cv2.imread("face.jpg")
# Convert image into grayscale
gray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
# Use detector to find landmarks
faces = detector(gray)
for face in faces:
    x1 = face.left() # left point
    y1 = face.top() # top point
    x2 = face.right() # right point
    y2 = face.bottom() # bottom point
    # Look for the landmarks
    landmarks = predictor(image=gray, box=face)
    x = landmarks.part(27).x
    y = landmarks.part(27).y
    # Draw a circle
    cv2.circle(img=img, center=(x, y), radius=5, color=(0, 255, 0), thickness=-1)
# show the image
cv2.imshow(winname="Face", mat=img)
# Wait for a key press to exit
cv2.waitKey(delay=0)
# Close all windows
cv2.destroyAllWindows()

像以前一樣,我們總是在同一個程式碼上構建程式碼,現在使用我們的預測函式為每個人臉找到地標。現在我還在做一些奇怪的事情,比如27號在那裡做什麼?

landmarks = predictor(image=gray, box=face)
x = landmarks.part(27).x
y = landmarks.part(27).y

我們的預測函式將返回一個包含所有68個點的物件,根據我們之前看到的圖片,如果你注意到的話,會發現點27正好在眼睛之間,所以如果所有的計算正確,你應該看到一個綠點在眼睛之間,如下圖所示:

我們已經很接近了,現在讓我們渲染所有的點,而不是隻渲染一個:

import cv2
import numpy as np
import dlib
# Load the detector
detector = dlib.get_frontal_face_detector()
# Load the predictor
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# read the image
img = cv2.imread("face.jpg")
# Convert image into grayscale
gray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
# Use detector to find landmarks
faces = detector(gray)
for face in faces:
    x1 = face.left() # left point
    y1 = face.top() # top point
    x2 = face.right() # right point
    y2 = face.bottom() # bottom point
    # Create landmark object
    landmarks = predictor(image=gray, box=face)
    # Loop through all the points
    for n in range(0, 68):
        x = landmarks.part(n).x
        y = landmarks.part(n).y
        # Draw a circle
        cv2.circle(img=img, center=(x, y), radius=3, color=(0, 255, 0), thickness=-1)
# show the image
cv2.imshow(winname="Face", mat=img)
# Delay between every fram
cv2.waitKey(delay=0)
# Close all windows
cv2.destroyAllWindows()

但是如果你對所有的點都不感興趣呢?實際上,你可以調整你的範圍間隔來獲得上面術語表中指定的任何特徵,就像我在這裡做的那樣:

太棒了,但我們能做點更酷的事嗎?

步驟4:實時檢測

是的,你沒看錯!這可能就是你想要的效果!下一步是連線我們的網路攝像頭,從你的視訊流中進行實時地標識別。

你可以通過使用相機遍歷視訊幀或使用視訊檔案來對面部進行實時面部地標檢測。

如果要使用自己的攝像機,請參考以下程式碼,如果使用的是視訊檔案,請確保將數字0更改為視訊路徑。

如果要結束視窗,請按鍵盤上的ESC鍵:

import cv2
import dlib

# Load the detector
detector = dlib.get_frontal_face_detector()

# Load the predictor
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

# read the image
cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    # Convert image into grayscale
    gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY)

    # Use detector to find landmarks
    faces = detector(gray)

    for face in faces:
        x1 = face.left()  # left point
        y1 = face.top()  # top point
        x2 = face.right()  # right point
        y2 = face.bottom()  # bottom point

        # Create landmark object
        landmarks = predictor(image=gray, box=face)

        # Loop through all the points
        for n in range(0, 68):
            x = landmarks.part(n).x
            y = landmarks.part(n).y

            # Draw a circle
            cv2.circle(img=frame, center=(x, y), radius=3, color=(0, 255, 0), thickness=-1)

    # show the image
    cv2.imshow(winname="Face", mat=frame)

    # Exit when escape is pressed
    if cv2.waitKey(delay=1) == 27:
        break

# When everything done, release the video capture and video write objects
cap.release()

# Close all windows
cv2.destroyAllWindows()

最後的結果是:

在弱光條件下,儘管上面的影象中有一些錯誤,但其結果也相當準確,如果照明效果好的話結果會更加準確。

結論

OpenCV和DLib是兩個功能非常強大的庫,它們簡化了ML和計算機視覺的工作,今天我們只是觸及了最基本的東西,還有很多東西需要從中學習。

非常感謝你的閱讀!

原文連結:https://towardsdatascience.com/detecting-face-features-with-python-30385aee4a8e

歡迎關注磐創AI部落格站:
http://panchuang.net/

sklearn機器學習中文官方文件:
http://sklearn123.com/

歡迎關注磐創部落格資源彙總站:
http://docs.panchuang.net/