Dlib人臉偵測

      在〈Dlib人臉偵測〉中尚無留言

人臉偵測就屬Dlib最為精準。Dlib是一套使用C++編寫的函式庫,應用在機器學習、影像處理以及影像辨識等功能,此套件為 Open Source 且是 free 的,license 是基於 BSD 授權條款。但安裝Python的Dlib套件時,是下載原始檔,然後再經過編譯。所以在Windows需安裝cmake及Visual Studio 2019的c++桌面開發。

Windows系統

CMake : https://cmake.org/download/ 請注意, CMake安裝完後, Pycharm需退出重新執行。

Visual Studio 2019 : 工具/取得工具與功能, 需安裝 使用 C++的桌面開發。請注意,一定要使用 VS2019及以前的版本。VS2020無法編譯出GPU的版本。

python_face_track1

Ubuntu

sudo apt-get install cmake python3-pip python3-opencv libopencv-dev

安裝Python相關模組

Python套件為 opencv-python numpy dlib。安裝opencv-python時會自動安裝 numpy

pip install opencv_python dlib

Python程式碼

讀取圖片可以使用OpenCV的imread()函數,然後將圖片丟給dlib 的dlib.get_frontal_face_detector 人臉偵測器(detector),即會傳回相關人臉的資訊。

detector函數的第二個參數是指定反取樣 (unsample) 的次數,預設值為 0。如果圖片太小,可將其設高一點,可提高偵測精準度,當然也較耗時間。

請注意,圖檔解析愈高,當然愈精準,但更加耗時。若縮小圖片再偵測,速度較快,但較不精準。此時就可以考慮提高反取樣參數。

detector 傳回的人臉資訊為 dlib.rectangle 資料結構list, 如
[(256,61)(654,100)]
此結構分別是左上角座標及右下角座標, 可以用left(), right()等函數分別取出

import cv2
import dlib
import numpy as np def resize(src, w=None, h=None, scale=1): if w is None or h is None: h, w = src.shape[:2] w = int(w * scale) h = int(h * scale) dst = cv2.resize(src, (w, h), interpolation=cv2.INTER_LINEAR) return dst img=cv2.imdecode(np.fromfile('face4.jpg', dtype=np.uint8), cv2.IMREAD_COLOR)
img=resize(img, scale=0.2) detector = dlib.get_frontal_face_detector() faces=detector(img, 1) for f in faces: x1=f.left() y1=f.top() x2=f.right() y2=f.bottom() img=cv2.rectangle(img, (x1, y1), (x2, y2), (0,255,0), 2, cv2.LINE_AA) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows()

python_face_track

偵測分數

Dlib 人臉偵測演算法使用方向梯度直方圖(HOG) 的特徵, 加上線性分類器(linear classifier)、影像金字塔(image pyramid) 與滑動窗格 (sliding window) 計算出來。演算的結果會有一個分數,此分數愈大,表示愈接近人臉。分數愈低表示愈接近誤判。調用detector.run() 即可取得分數

faces, scores, indexs = detector.run(img, 1, 0.5)

上述第二個參數為反取樣次數,第三個參數為分數的門檻值,要超過 0.5 才會列出。至於返回值 indexs 為子偵測器的編號,用來判斷人臉的方向,詳細說明請看官網

完整代碼如下

import cv2
import dlib
def resize(src, w=None, h=None, scale=1):
    if w is None or h is None:
        h, w = src.shape[:2]
        w = int(w * scale)
        h = int(h * scale)
    dst = cv2.resize(src, (w, h), interpolation=cv2.INTER_LINEAR)
    return dst
img=cv2.imdecode(np.fromfile('face4.jpg', dtype=np.uint8), cv2.IMREAD_COLOR)
img=resize(img, scale=0.3)
detector = dlib.get_frontal_face_detector()
faces, scores, indexs=detector.run(img, 1, 0.5)
print(faces)
print(scores)
print(indexs)
for i, f in enumerate(faces):
    x1=f.left()
    y1=f.top()
    x2=f.right()
    y2=f.bottom()
    img=cv2.rectangle(img, (x1, y1), (x2, y2), (0,255,0), 2, cv2.LINE_AA)
    text = f"{indexs[i]}({scores[i]:2.2f})"
    cv2.putText(img, text, (x1, y1-5), cv2.FONT_HERSHEY_DUPLEX, 0.4, (0, 0, 255), 1,)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

web cam人臉偵測

代碼跟上面差不多,只是圖片由 cv2.VideoCapture(0)提供

import cv2
import dlib
cam=cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
while True:
    success,img=cam.read()
    faces, scores, indexs=detector.run(img, 0, 0)
    for i, f in enumerate(faces):
        x1=f.left()
        y1=f.top()
        x2=f.right()
        y2=f.bottom()
        img=cv2.rectangle(img, (x1, y1), (x2, y2), (0,255,0), 2, cv2.LINE_AA)
        text = f"{indexs[i]}({scores[i]:2.2f})"
        cv2.putText(img, text, (x1, y1-5), cv2.FONT_HERSHEY_DUPLEX, 0.4, (0, 0, 255), 1,)
    cv2.imshow("Video", img)
    key=cv2.waitKey(10)
    if key==ord('q') or key==27:
        break;
cam.release()
cv2.destroyAllWindows()

Dlib GPU版

Dlib自19.21.0版開始,只要有安裝nVidia顯卡及CUDA,就會自動改為GPU計算,不需自行編譯。但是在安裝Dlib前,要先安裝CMake 及 Visual Studio 2019的版本請注意,絕對不能使用 Visual Studio 2022的版本,否則 dlib.DLIB_USE_CUDA 一定是 False。

如果不小心安裝了 VS 2022,又安裝了 Dlib,則要先移除 VS 2022,改安裝 VS 2019。然後重裝Dlib時,此時又會使用 Python cache 安裝先前Dlib 錯誤的版本。所以在Python 重新安裝Dlib時,要下達如下指令

pip uninstall dlib
pip install dlib --no-cache-dir

在偵測人臉位置時,需改用 dlib.cnn_face_detection_model_v1 卷積神經網路人臉偵測器,此偵測器需載入 mmod_human_face_detector.data 人臉訓練資料。cnn_face_detection_model_v1比get_frontal_face_detector更加的精準,但也更加的費時,所以若沒有GPU支援的話,效能非常的差。

人臉訓練資料請由如下網址下載 :  mmod_human_face_detector.bz2

import cv2
import dlib
print(dlib.DLIB_USE_CUDA)
print(dlib.cuda.get_num_devices())
cam=cv2.VideoCapture('魔鬼終結者6.黑暗宿命.Terminator.Dark.Fate.2019.1080p.mp4')
cam.set(cv2.CAP_PROP_POS_MSEC, 900000)
#detector = dlib.get_frontal_face_detector()
detector=dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')
while True:
success,img=cam.read()
h, w = img.shape[:2]
h = int(h * 0.4)
w = int(w * 0.4)
img = cv2.resize(img, (w, h), cv2.LINE_AA)
#faces, scores, indexs=detector.run(img, 1, 0)
faces=detector(img, 0)
for i, d in enumerate(faces):
f=d.rect
x1=f.left()
y1=f.top()
x2=f.right()
y2=f.bottom()
img=cv2.rectangle(img, (x1, y1), (x2, y2), (0,255,0), 2, cv2.LINE_AA)
#text = f"{indexs[i]}({scores[i]:2.2f})"
#cv2.putText(img, text, (x1, y1-5), cv2.FONT_HERSHEY_DUPLEX, 0.4, (0, 0, 255), 1,)
cv2.imshow("Video", img)
key=cv2.waitKey(1)
if key==ord('q') or key==27:
break;
cam.release()
cv2.destroyAllWindows()

但如果是19.20.0 及之前的版本,就需使用如下方法編譯 GPU 的版本。所以最好安裝目前最新的 19.22.1。底下只是記錄一下而以。

1.  請到官網下載dlib原始碼 http://dlib.net/

2. 解開dlib壓縮檔到專案目錄之下,這邊以 dlib-19.22.zip說明

3. 進入DOS,進入專案目錄之下,輸入如下指令

venv\Scripts\activate
cd dlib-19.22
mkdir build
cd build
cmake .. -DDLIB_USE_CUDA=1 -DUSE_AVX_INSTRUCTIONS=1
cmake --build .
cd ..
python setup.py install --set USE_AVX_INSTRUCTIONS=1 --set DLIB_USE_CUDA=1

4. 安裝nVidia CUDA套件,請參照 TensorFlow安裝

5. 在Pycharm撰寫如下代碼驗証

import dlib
print(dlib.DLIB_USE_CUDA)
print(dlib.cuda.get_num_devices())
結果 :
True
1

發佈留言