使用Python和dlib進(jìn)行人臉檢測
“Dlib是一個(gè)現(xiàn)代化的C ++工具包,包含用于創(chuàng)建復(fù)雜軟件的機(jī)器學(xué)習(xí)算法和工具”。它使您能夠直接在Python中運(yùn)行許多任務(wù),其中一個(gè)例子就是人臉檢測。
安裝dlib并不像只做一個(gè)“pip install dlib”那么簡單,因?yàn)橐_配置和編譯dlib,您首先需要安裝其他系統(tǒng)依賴項(xiàng)。如果你按照這里描述的步驟,它應(yīng)該很容易讓dlib啟動(dòng)并運(yùn)行。(在本文中,我將介紹如何在Mac上安裝dlib,但如果您使用的是Ubuntu,請務(wù)必查看相關(guān)資源部分的鏈接。)
你需要確定的***件事是你已經(jīng)安裝和更新了Hombrew。如果您需要安裝它,請將其粘貼到終端中:
- $ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
或者,如果您需要更新Hombrew,請輸入以下內(nèi)容:
- $ brew update
您現(xiàn)在可以使用Homebrew來安裝CMake,Boost.Python,以及在您的系統(tǒng)中正確配置和編譯dlib所需的兩個(gè)依賴關(guān)系:
- $ brew install cmake
- $ brew install boost-python
***,您需要手動(dòng)下載并安裝XQuartz。
您現(xiàn)在已準(zhǔn)備好安裝dlib。我們將通過首先為這個(gè)項(xiàng)目創(chuàng)建一個(gè)孤立的虛擬環(huán)境來做到這一點(diǎn)。我將使用virtualenv,但您可以使用任何您熟悉的虛擬環(huán)境工具,包括Python的venv模塊。需要scikit-image庫才能讀取我們稍后將傳遞給dlib的圖像文件,因此我們還需要pip安裝它:
- $ virtualenv venv_dlib
- $ source venv_dlib / bin / activate
- $ pip install scikit-image
- $ pip install dlib
就是這樣。有了這個(gè),你應(yīng)該有可用的dlib。
Dlib
Dlib提供了不同的臉部檢測算法。我將在這里使用的是基于CNN的人臉檢測器。您可以下載預(yù)訓(xùn)練模型:https://github.com/davisking/dlib-models。由于使用此模型的計(jì)算成本很高,因此***在GPU上執(zhí)行以下代碼。使用CPU也可以,但速度會(huì)更慢。
要在下面的要點(diǎn)中運(yùn)行人臉檢測代碼,我建議首先在虛擬環(huán)境中再安裝兩個(gè)庫。這些庫將使與代碼交互和可視化結(jié)果更容易:
- $ pip install matplotlib
- $ pip install jupyterlab
安裝完庫后,您需要確保:
- 下載預(yù)訓(xùn)練模型(http://dlib.net/files/mmod_human_face_detector.dat.bz2)并將其存儲(chǔ)在項(xiàng)目的根目錄中
- 創(chuàng)建一個(gè)名為'faces'的新目錄,在該目錄中存儲(chǔ)帶有希望檢測的臉部的.jpg。
有了這個(gè),你終于準(zhǔn)備好開始在圖片中檢測臉部了!您可以通過在Jupyter Notebook中運(yùn)行以下代碼來完成此操作
- import dlib
- import matplotlib.patches as patches
- import matplotlib.pyplot as plt
- from pathlib import Path
- from skimage import io
- %matplotlib inline
- # Load trained model
- cnn_face_detector = dlib.cnn_face_detection_model_v1(
- 'mmod_human_face_detector.dat')
- # Function to detect and show faces in images
- def detect_face_dlib(img_path, ax):
- # Read image and run algorithm
- img = io.imread(img_path)
- dets = cnn_face_detector(img, 1)
- # If there were faces detected, show them
- if len(dets) > 0:
- for d in dets:
- rect = patches.Rectangle(
- (d.rect.left(), d.rect.top()),
- d.rect.width(),
- d.rect.height(),
- fill=False,
- color='b',
- lw='2')
- ax.add_patch(rect)
- ax.imshow(img)
- ax.set_title(str(img_path).split('/')[-1])
- # Path to images
- images = list(Path('faces').glob('*.jpg'))
- # Show results
- fig = plt.figure(figsize=(15, 5))
- for i, img in enumerate(images):
- ax = fig.add_subplot(1, len(images), i+1)
- detect_face_dlib(img, ax)
結(jié)果
在運(yùn)行代碼之后,您應(yīng)該看到圖像中的臉部周圍出現(xiàn)藍(lán)色方塊,如果您問我,考慮到我們只寫了幾行代碼,這非常棒!