使用Python和dlib進行人臉檢測
“Dlib是一個現(xiàn)代化的C ++工具包,包含用于創(chuàng)建復雜軟件的機器學習算法和工具”。它使您能夠直接在Python中運行許多任務,其中一個例子就是人臉檢測。
安裝dlib并不像只做一個“pip install dlib”那么簡單,因為要正確配置和編譯dlib,您首先需要安裝其他系統(tǒng)依賴項。如果你按照這里描述的步驟,它應該很容易讓dlib啟動并運行。(在本文中,我將介紹如何在Mac上安裝dlib,但如果您使用的是Ubuntu,請務必查看相關(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所需的兩個依賴關(guān)系:
- $ brew install cmake
- $ brew install boost-python
***,您需要手動下載并安裝XQuartz。
您現(xiàn)在已準備好安裝dlib。我們將通過首先為這個項目創(chuàng)建一個孤立的虛擬環(huá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
就是這樣。有了這個,你應該有可用的dlib。
Dlib
Dlib提供了不同的臉部檢測算法。我將在這里使用的是基于CNN的人臉檢測器。您可以下載預訓練模型:https://github.com/davisking/dlib-models。由于使用此模型的計算成本很高,因此***在GPU上執(zhí)行以下代碼。使用CPU也可以,但速度會更慢。
要在下面的要點中運行人臉檢測代碼,我建議首先在虛擬環(huán)境中再安裝兩個庫。這些庫將使與代碼交互和可視化結(jié)果更容易:
- $ pip install matplotlib
- $ pip install jupyterlab
安裝完庫后,您需要確保:
- 下載預訓練模型(http://dlib.net/files/mmod_human_face_detector.dat.bz2)并將其存儲在項目的根目錄中
- 創(chuàng)建一個名為'faces'的新目錄,在該目錄中存儲帶有希望檢測的臉部的.jpg。
有了這個,你終于準備好開始在圖片中檢測臉部了!您可以通過在Jupyter Notebook中運行以下代碼來完成此操作
- 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é)果
在運行代碼之后,您應該看到圖像中的臉部周圍出現(xiàn)藍色方塊,如果您問我,考慮到我們只寫了幾行代碼,這非常棒!