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

今天,我們將學習如何檢測圖像中的人臉並提取面部特征,如眼睛、鼻子、嘴巴等。我們可以將這些信息作為一個預處理步驟來完成,例如捕捉照片中人物的人臉(手動或通過機器學習),創建效果來“增強”我們的圖像(類似於Snapchat等應用程序中的效果),對人臉進行情感分析等等。
過去,我們已經討論過如何使用OpenCV來檢測圖像中的形狀,但是今天我們將通過引入DLib和從圖像中提取面部特征來將其提升到一個新的水平。
Dlib是一個高級的機器學習庫,它是為解決復雜的現實世界問題而創建的。這個庫是用C++編程語言創建的,它與C/C++、Python和java一起工作。
- Dlib:http://dlib.net/
值得注意的是,本教程可能需要對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/
