那個(gè)網(wǎng)站可以接做網(wǎng)頁(yè)私活惠州網(wǎng)絡(luò)營(yíng)銷公司
前言
隨著金秋時(shí)節(jié)的來(lái)臨,國(guó)慶和中秋的雙重喜慶匯聚成一片溫暖的節(jié)日氛圍。在這個(gè)美好的時(shí)刻,我們有幸共同迎來(lái)一次長(zhǎng)達(dá)8天的假期,為心靈充電,為身體放松,為未來(lái)充實(shí)自己。今年的國(guó)慶不僅僅是家國(guó)團(tuán)聚的時(shí)刻,更是展現(xiàn)自我的舞臺(tái)。我在這個(gè)特殊的假期里,決定探究dlib模型用法,并將在這篇文章中分享我的學(xué)習(xí)過(guò)程和心得體會(huì)。
在上一篇文章中,我們成功跨平臺(tái)成功配置了dlib庫(kù)
全面橫掃:dlib Python API在Linux和Windows的配置方案
本文基于人臉識(shí)別系統(tǒng)項(xiàng)目繼續(xù)拓展,嘗試添加dlib庫(kù)相關(guān)功能進(jìn)行二合一
Retinaface+FaceNet人臉識(shí)別系統(tǒng)-Gradio界面設(shè)計(jì)
文章目錄
- 前言
- VMware攝像頭調(diào)用方法
- 運(yùn)行環(huán)境配置
- 13個(gè)模型逐個(gè)分析
- 模型下載
- 13個(gè)模型的示例程序
- 1.dlib_face_recognition_resnet_model_v1.dat
- 2. **mmod_dog_hipsterizer.dat.bz2**
- 3. **mmod_human_face_detector.dat.bz2:**
- 4. **resnet34_1000_imagenet_classifier.dnn.bz2:**
- 5. **shape_predictor_5_face_landmarks.dat.bz2:**
- 6. **shape_predictor_68_face_landmarks.dat.bz2:**
- 7. **shape_predictor_68_face_landmarks_GTX.dat.bz2:**
- 8. **mmod_rear_end_vehicle_detector.dat.bz2:**
- 9. **mmod_front_and_rear_end_vehicle_detector.dat.bz2:**
- 10. **dnn_gender_classifier_v1.dat.bz2:**
- 11. **dnn_age_predictor_v1.dat.bz2:**
- 12. **resnet50_1000_imagenet_classifier.dnn.bz2:**
- 13. **dcgan_162x162_synth_faces.dnn.bz2:**
- 實(shí)用技巧
- 眨眼次數(shù)記錄
- 下一步嘗試
- 寫給自己(關(guān)閉gpu加速僅在cpu上加載模型)
- 總結(jié)
VMware攝像頭調(diào)用方法
- VMware怎么調(diào)中文
網(wǎng)上的教程大多都說(shuō)右鍵快捷方式打開(kāi)屬性,然后再vmware.exe后加一個(gè)空格再加上–locale zh_CN,我開(kāi)始測(cè)試時(shí)不管用,后來(lái)?yè)Q成兩個(gè)空格,即
快捷方式末尾添加兩個(gè)空格然后加
--locale zh_CN
-
調(diào)整虛擬機(jī)USB設(shè)置:
- 進(jìn)入虛擬機(jī)設(shè)置。
- 轉(zhuǎn)至硬件選項(xiàng),選擇USB控制器。
- 在USB兼容性選項(xiàng)中,設(shè)置為USB3.1。
-
在VMware Workstation中配置虛擬機(jī)攝像頭:
- 打開(kāi)虛擬機(jī),找到虛擬機(jī)(M)。
- 移動(dòng)鼠標(biāo)到可移動(dòng)設(shè)置,找到圖像設(shè)備。
- 在圖像設(shè)備中,確保攝像頭選項(xiàng)已啟用。
-
進(jìn)行虛擬機(jī)設(shè)置:
- 打開(kāi)終端并輸入以下命令:
sudo apt-get install cheese cheese
- 測(cè)試攝像頭是否連接成功,在終端輸入命令,如果看到video0,表示連接成功:
ls /dev/video0
- 安裝ffmpeg:
sudo apt-get install ffmpeg
- 使用以下命令測(cè)試攝像頭:
ffplay -i /dev/video0
- 打開(kāi)終端并輸入以下命令:
以上步驟確保了你的虛擬機(jī)攝像頭能夠成功連接,并且通過(guò)ffmpeg進(jìn)行測(cè)試。
運(yùn)行環(huán)境配置
打包方式基于
半自動(dòng)化使用.bat手動(dòng)打包遷移python項(xiàng)目
- Python 3.8
- OpenCV
- Pytorch
- dlib
- gradio
rem 創(chuàng)建虛擬環(huán)境
python -m venv venv
call venv\Scripts\activate.bat
python -m pip install -i https://mirrors.aliyun.com/pypi/simple/ --upgrade pip setuptools
pip install dlib-19.19.0-cp38-cp38-win_amd64.whl
pip install -i https://mirrors.aliyun.com/pypi/simple/ opencv-python==4.5.3.56
pip install torch-1.7.1+cu110-cp38-cp38-win_amd64.whl
pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
pip install -i https://mirrors.aliyun.com/pypi/simple/ gradio
pip install -i https://mirrors.aliyun.com/pypi/simple/ scikit-learn
pip install -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt
requirements.txt
scipy==1.7.1
numpy==1.21.2
matplotlib==3.4.3
opencv_python==4.5.3.56
torch==1.7.1
torchvision==0.8.2
tqdm==4.62.2
Pillow==8.3.2
h5py==2.10.0
我搜集了python3.7-3.9各種版本的dlib安裝包你可以關(guān)注我然后回復(fù)我dlib獲取
dlib
我搜集了python3.7-3.9各種版本的dlib安裝包
dlib-19.17.99-cp37-cp37m-win_amd64.whl
dlib-19.24.2-cp37-cp37m-win_amd64.whl
dlib-19.19.0-cp38-cp38-win_amd64.whl
dlib-19.21.99-cp38-cp38-win_amd64.whl
dlib-19.22.99-cp39-cp39-win_amd64.whl
這里我們使用dlib-19.19.0-cp38-cp38-win_amd64.whl測(cè)試
rem 創(chuàng)建虛擬環(huán)境
python -m venv venv
call venv\Scripts\activate.bat
python -m pip install -i https://mirrors.aliyun.com/pypi/simple/ --upgrade pip setuptools
pip install dlib-19.19.0-cp38-cp38-win_amd64.whl
13個(gè)模型逐個(gè)分析
官方GitHub連接
dlib
dlib-models
"dlib-models"倉(cāng)庫(kù)中的訓(xùn)練模型由Davis King創(chuàng)建,主要用于計(jì)算機(jī)視覺(jué)和人臉識(shí)別等各種任務(wù)。以下是每個(gè)模型及其特點(diǎn)的簡(jiǎn)要總結(jié):
-
dlib_face_recognition_resnet_model_v1.dat.bz2:
- 描述:一個(gè)具有29個(gè)卷積層的ResNet網(wǎng)絡(luò),改編自ResNet-34架構(gòu)。從頭開(kāi)始訓(xùn)練,使用了約300萬(wàn)張臉部圖像,數(shù)據(jù)來(lái)自多個(gè)來(lái)源,包括face scrub、VGG數(shù)據(jù)集和從互聯(lián)網(wǎng)上抓取的圖像。
- 用途:人臉識(shí)別。
- 性能:在LFW基準(zhǔn)測(cè)試中,平均誤差為0.993833,標(biāo)準(zhǔn)差為0.00272732。
-
mmod_dog_hipsterizer.dat.bz2:
- 描述:基于Columbia Dogs數(shù)據(jù)集訓(xùn)練,用于狗的品種分類和部位定位。
- 用途:狗的品種分類以及可能與狗圖像相關(guān)的其他任務(wù)。
-
mmod_human_face_detector.dat.bz2:
- 描述:在包括ImageNet、AFLW、Pascal VOC、VGG數(shù)據(jù)集、WIDER和face scrub在內(nèi)的多個(gè)公開(kāi)可用圖像數(shù)據(jù)集中找到的人臉圖像創(chuàng)建的數(shù)據(jù)集。標(biāo)注是使用dlib的imglab工具創(chuàng)建的。
- 用途:人臉檢測(cè)。
-
resnet34_1000_imagenet_classifier.dnn.bz2:
- 描述:在ImageNet數(shù)據(jù)集上訓(xùn)練。
- 用途:通用圖像分類。
-
shape_predictor_5_face_landmarks.dat.bz2:
- 描述:一個(gè)5點(diǎn)面部標(biāo)記模型,用于識(shí)別眼睛角和鼻子底部。使用從互聯(lián)網(wǎng)下載的圖像并使用dlib的imglab工具進(jìn)行標(biāo)注創(chuàng)建的數(shù)據(jù)集進(jìn)行訓(xùn)練。
- 用途:面部特征定位,與dlib的HOG人臉檢測(cè)器和CNN人臉檢測(cè)器兼容。
-
shape_predictor_68_face_landmarks.dat.bz2:
- 描述:在ibug 300-W數(shù)據(jù)集上訓(xùn)練,用于精確的面部特征定位,最適合與dlib的HOG人臉檢測(cè)器一起使用。
-
shape_predictor_68_face_landmarks_GTX.dat.bz2:
- 描述:具有增強(qiáng)的面部檢測(cè)器魯棒性的68點(diǎn)面部標(biāo)記模型。
- 用途:精確的面部特征定位,優(yōu)化用于方形邊界框。
-
mmod_rear_end_vehicle_detector.dat.bz2:
- 描述:在包括車輛儀表板攝像頭圖像的后端車輛圖像上手動(dòng)注釋的數(shù)據(jù)集上進(jìn)行訓(xùn)練。
- 用途:后端車輛檢測(cè)。
-
mmod_front_and_rear_end_vehicle_detector.dat.bz2:
- 描述:在包括車輛儀表板攝像頭圖像的前端和后端車輛圖像上手動(dòng)注釋的數(shù)據(jù)集上進(jìn)行訓(xùn)練。
- 用途:前端和后端車輛檢測(cè)。
-
dnn_gender_classifier_v1.dat.bz2:
- 描述:使用約20萬(wàn)張不同臉部圖像的私有數(shù)據(jù)集訓(xùn)練的性別分類器。
- 用途:從面部圖像進(jìn)行性別預(yù)測(cè)。
-
dnn_age_predictor_v1.dat.bz2:
- 描述:基于ResNet-10架構(gòu)訓(xùn)練的年齡預(yù)測(cè)器,使用約11萬(wàn)張不同標(biāo)記圖像進(jìn)行訓(xùn)練,性能超越了最新的結(jié)果。
- 用途:從面部圖像進(jìn)行年齡估計(jì)。
-
resnet50_1000_imagenet_classifier.dnn.bz2:
- 描述:使用ResNet50模型定義在resnet.h中,在ImageNet數(shù)據(jù)集上進(jìn)行訓(xùn)練。
- 用途:通用圖像分類。
-
dcgan_162x162_synth_faces.dnn.bz2:
- 描述:使用深度卷積生成對(duì)抗網(wǎng)絡(luò)(DCGAN)架構(gòu)訓(xùn)練的DCGAN面部合成模型,用于生成逼真的合成彩色面部圖像。
請(qǐng)注意,這些模型的使用和許可可能會(huì)有所不同,因此務(wù)必仔細(xì)閱讀提供的信息,并確保遵守任何提到的限制。這些模型可以用于各種計(jì)算機(jī)視覺(jué)任務(wù),是寶貴的資源。
模型下載
我們直接使用git
git clone https://github.com/davisking/dlib-models.git
當(dāng)使用dlib的dlib_face_recognition_resnet_model_v1.dat
模型進(jìn)行人臉識(shí)別時(shí),你需要安裝dlib庫(kù)并加載該模型。以下是一個(gè)Python示例代碼,演示如何使用該模型進(jìn)行簡(jiǎn)單的人臉識(shí)別:
首先,確保你已經(jīng)安裝了dlib庫(kù)。你可以使用以下命令安裝:
pip install dlib
然后,你可以使用以下Python代碼進(jìn)行人臉識(shí)別:
import dlib
from skimage import io# 加載dlib_face_recognition_resnet_model_v1.dat模型
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 這里你也可以使用其他人臉關(guān)鍵點(diǎn)模型
facerec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")# 加載測(cè)試圖像
img = io.imread("test_image.jpg")# 在圖像中檢測(cè)人臉
dets = detector(img, 1)# 如果檢測(cè)到多個(gè)人臉,可以迭代處理每一個(gè)人臉
for i, d in enumerate(dets):shape = sp(img, d) # 獲取關(guān)鍵點(diǎn)face_descriptor = facerec.compute_face_descriptor(img, shape) # 獲取人臉描述符# 在這里,你可以與數(shù)據(jù)庫(kù)中的人臉描述符進(jìn)行比對(duì),實(shí)現(xiàn)人臉識(shí)別# 例如,計(jì)算當(dāng)前人臉描述符與數(shù)據(jù)庫(kù)中存儲(chǔ)的描述符的歐氏距離,找到最接近的匹配# 打印人臉描述符print(f"Face Descriptor for Face {i + 1}:")print(face_descriptor)# 在這里,你可以根據(jù)你的需求進(jìn)行人臉識(shí)別匹配
請(qǐng)注意,上述示例中使用的是shape_predictor_68_face_landmarks.dat
模型來(lái)獲取人臉關(guān)鍵點(diǎn),然后使用dlib_face_recognition_resnet_model_v1.dat
模型來(lái)計(jì)算人臉描述符。你可以根據(jù)需要使用不同的關(guān)鍵點(diǎn)模型和匹配算法來(lái)進(jìn)行人臉識(shí)別。還需要將test_image.jpg
替換為你要測(cè)試的圖像文件的路徑。
13個(gè)模型的示例程序
1.dlib_face_recognition_resnet_model_v1.dat
當(dāng)使用dlib的dlib_face_recognition_resnet_model_v1.dat
模型進(jìn)行人臉識(shí)別時(shí),你需要安裝dlib庫(kù)并加載該模型。以下是一個(gè)Python示例代碼,演示如何使用該模型進(jìn)行簡(jiǎn)單的人臉識(shí)別:
首先,確保你已經(jīng)安裝了scikit-image庫(kù)。你可以使用以下命令安裝:
pip install scikit-image
文件夾結(jié)構(gòu): 將用戶圖像存儲(chǔ)在以用戶名稱命名的文件夾中,這樣可以更輕松地組織用戶數(shù)據(jù)。例如,用戶1的圖像存儲(chǔ)在名為 user1 的文件夾中,用戶2的圖像存儲(chǔ)在名為 user2 的文件夾中。
1. 注冊(cè)用戶的人臉描述符生成代碼:
import dlib
import numpy as np
import os
from skimage import io
import pickle# 加載dlib_face_recognition_resnet_model_v1.dat模型
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 這里你也可以使用其他人臉關(guān)鍵點(diǎn)模型
facerec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")# 初始化一個(gè)字典來(lái)存儲(chǔ)已注冊(cè)用戶的人臉描述符
registered_faces = {}# 指定用戶圖像所在的文件夾
user_images_folder = "user_images"# 遍歷用戶圖像文件夾
for user_folder in os.listdir(user_images_folder):if os.path.isdir(os.path.join(user_images_folder, user_folder)):user_name = user_folder # 使用文件夾名稱作為用戶名稱# 初始化一個(gè)列表來(lái)存儲(chǔ)當(dāng)前用戶的人臉描述符user_face_descriptors = []# 遍歷用戶文件夾中的圖像文件for user_image_file in os.listdir(os.path.join(user_images_folder, user_folder)):if user_image_file.endswith(".jpg"):user_image_path = os.path.join(user_images_folder, user_folder, user_image_file)# 從用戶圖像中讀取圖像user_img = io.imread(user_image_path)# 在圖像中檢測(cè)人臉dets = detector(user_img, 1)# 如果檢測(cè)到一個(gè)人臉,假設(shè)只有一個(gè)人臉if len(dets) == 1:shape = sp(user_img, dets[0]) # 獲取關(guān)鍵點(diǎn)face_descriptor = facerec.compute_face_descriptor(user_img, shape) # 獲取人臉描述符user_face_descriptors.append(np.array(face_descriptor))# 存儲(chǔ)用戶的人臉描述符到已注冊(cè)用戶的字典registered_faces[user_name] = user_face_descriptors# 將已注冊(cè)用戶的人臉描述符保存到本地文件
with open("registered_faces.pkl", "wb") as f:pickle.dump(registered_faces, f)print("Registration completed.")
2. 人臉識(shí)別代碼:
import dlib
import numpy as np
from skimage import io
import pickle
import cv2# 加載dlib_face_recognition_resnet_model_v1.dat模型
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 這里你也可以使用其他人臉關(guān)鍵點(diǎn)模型
facerec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")# 加載已注冊(cè)用戶的人臉描述符
with open("registered_faces.pkl", "rb") as f:registered_faces = pickle.load(f)# 設(shè)定一個(gè)閾值,用于確定匹配是否成功,閾值越小,匹配越嚴(yán)格
threshold = 0.6# 加載測(cè)試圖像
test_image_path = "test.jpg"
img = io.imread(test_image_path)# 在圖像中檢測(cè)人臉
dets = detector(img, 1)# 初始化一個(gè)列表來(lái)存儲(chǔ)匹配結(jié)果
matches = []# 遍歷檢測(cè)到的人臉描述符
for i, d in enumerate(dets):shape = sp(img, d) # 獲取關(guān)鍵點(diǎn)face_descriptor = facerec.compute_face_descriptor(img, shape) # 獲取人臉描述符# 初始化最佳匹配信息best_match_name = "Unknown"best_match_distance = float("inf")# 遍歷已注冊(cè)用戶的數(shù)據(jù)庫(kù)for name, registered_descriptors in registered_faces.items():for registered_descriptor in registered_descriptors:# 計(jì)算當(dāng)前人臉描述符與已注冊(cè)用戶的歐氏距離distance = np.linalg.norm(np.array(face_descriptor) - np.array(registered_descriptor))# 如果距離小于閾值,并且比當(dāng)前最佳匹配距離更近if distance < threshold and distance < best_match_distance:best_match_name = namebest_match_distance = distance# 將匹配結(jié)果添加到列表matches.append({"face_id": i + 1, "user_name": best_match_name, "distance": best_match_distance})# 在圖像上繪制匹配結(jié)果
for match in matches:face_id = match["face_id"]user_name = match["user_name"]distance = match["distance"]# 繪制人臉框x, y, w, h = d.left(), d.top(), d.width(), d.height()cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)# 在人臉框上方顯示匹配結(jié)果text = f"Face {face_id}: {user_name} ({distance:.2f})"cv2.putText(img, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)# 顯示帶有匹配結(jié)果的圖像
cv2.imshow("Face Recognition", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
確保根據(jù)你的需求將這些代碼片段中的變量和文件路徑進(jìn)行適當(dāng)?shù)奶鎿Q。這兩段代碼現(xiàn)在應(yīng)該能夠正常運(yùn)行并進(jìn)行人臉識(shí)別。如果你有其他問(wèn)題或需要進(jìn)一步的幫助,請(qǐng)隨時(shí)提問(wèn)。
2. mmod_dog_hipsterizer.dat.bz2
import dlib
import cv2
from skimage import io# 加載 dlib_face_recognition_resnet_model_v1.dat 模型用于關(guān)鍵點(diǎn)檢測(cè)
shape_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")# 加載測(cè)試圖像
img = io.imread("test.jpg")# 加載 mmod_dog_hipsterizer.dat 模型
detector = dlib.get_frontal_face_detector()
hip_detector = dlib.cnn_face_detection_model_v1("mmod_dog_hipsterizer.dat")# 使用檢測(cè)器檢測(cè)狗的品種和部位
detections = hip_detector(img, 1)# 遍歷檢測(cè)結(jié)果并繪制矩形框
for detection in detections:x, y, w, h = detection.rect.left(), detection.rect.top(), detection.rect.width(), detection.rect.height()# 繪制矩形框cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)# 使用關(guān)鍵點(diǎn)檢測(cè)器獲取部位關(guān)鍵點(diǎn)landmarks = shape_predictor(img, detection.rect)# 遍歷關(guān)鍵點(diǎn)并繪制for point in landmarks.parts():cv2.circle(img, (point.x, point.y), 2, (0, 0, 255), -1)# 顯示帶有檢測(cè)結(jié)果和關(guān)鍵點(diǎn)的圖像
cv2.imshow("Dog Hipsterizer", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import dlib
from skimage import io# 加載模型
detector = dlib.cnn_face_detection_model_v1("mmod_dog_hipsterizer.dat")# 加載要分類的狗的圖像
dog_image = io.imread("dog2.jpg")# 運(yùn)行分類器來(lái)檢測(cè)品種
detections = detector(dog_image)# 打印每個(gè)檢測(cè)到的品種
for detection in detections:# 檢測(cè)到的品種的置信度可以通過(guò)矩形的面積來(lái)估計(jì)confidence = detection.rect.area()print(f"品種:{detection.rect}, 置信度:{confidence}")# 如果需要,可以進(jìn)一步解析品種的標(biāo)簽以獲得可讀的結(jié)果
3. mmod_human_face_detector.dat.bz2:
import dlib
import cv2# 加載模型
detector = dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat")# 加載要進(jìn)行人臉檢測(cè)的圖像
image = cv2.imread("test.jpg")# 將圖像轉(zhuǎn)換為灰度圖像(dlib要求輸入為灰度圖像)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用模型進(jìn)行人臉檢測(cè)
detections = detector(gray)# 在原圖上繪制檢測(cè)到的人臉矩形框
for detection in detections:x, y, w, h = (detection.rect.left(), detection.rect.top(), detection.rect.width(), detection.rect.height())cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)# 顯示帶有人臉檢測(cè)結(jié)果的圖像
cv2.imshow("Face Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
4. resnet34_1000_imagenet_classifier.dnn.bz2:
暫未找到python調(diào)用方法
5. shape_predictor_5_face_landmarks.dat.bz2:
import dlib
import cv2# 加載面部特征定位模型
predictor = dlib.shape_predictor("shape_predictor_5_face_landmarks.dat")# 加載圖像
image = cv2.imread("test.jpg")# 將圖像轉(zhuǎn)換為灰度
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用dlib的HOG人臉檢測(cè)器檢測(cè)人臉
detector = dlib.get_frontal_face_detector()
faces = detector(gray)# 對(duì)每個(gè)檢測(cè)到的人臉進(jìn)行面部特征定位
for face in faces:landmarks = predictor(gray, face)# 獲取并繪制每個(gè)關(guān)鍵點(diǎn)for n in range(5): # 此模型僅包含5個(gè)關(guān)鍵點(diǎn)x = landmarks.part(n).xy = landmarks.part(n).ycv2.circle(image, (x, y), 2, (0, 255, 0), -1)# 顯示帶有關(guān)鍵點(diǎn)的圖像
cv2.imshow("Facial Landmarks", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
6. shape_predictor_68_face_landmarks.dat.bz2:
import dlib
import cv2# 加載面部特征定位模型
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")# 加載圖像
image = cv2.imread("test.jpg")# 將圖像轉(zhuǎn)換為灰度
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用dlib的HOG人臉檢測(cè)器檢測(cè)人臉
detector = dlib.get_frontal_face_detector()
faces = detector(gray)# 對(duì)每個(gè)檢測(cè)到的人臉進(jìn)行面部特征定位
for face in faces:landmarks = predictor(gray, face)# 獲取并繪制每個(gè)關(guān)鍵點(diǎn)for n in range(68): # 此模型包含68個(gè)關(guān)鍵點(diǎn)x = landmarks.part(n).xy = landmarks.part(n).ycv2.circle(image, (x, y), 2, (0, 255, 0), -1)# 顯示帶有關(guān)鍵點(diǎn)的圖像
cv2.imshow("Facial Landmarks", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
7. shape_predictor_68_face_landmarks_GTX.dat.bz2:
import dlib
import cv2# 加載面部特征定位模型
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks_GTX.dat")# 加載圖像
image = cv2.imread("test.jpg")# 將圖像轉(zhuǎn)換為灰度
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用dlib的HOG人臉檢測(cè)器檢測(cè)人臉
detector = dlib.get_frontal_face_detector()
faces = detector(gray)# 對(duì)每個(gè)檢測(cè)到的人臉進(jìn)行面部特征定位
for face in faces:landmarks = predictor(gray, face)# 獲取并繪制每個(gè)關(guān)鍵點(diǎn)for n in range(68): # 此模型包含68個(gè)關(guān)鍵點(diǎn)x = landmarks.part(n).xy = landmarks.part(n).ycv2.circle(image, (x, y), 2, (0, 255, 0), -1)# 顯示帶有關(guān)鍵點(diǎn)的圖像
cv2.imshow("Facial Landmarks", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
8. mmod_rear_end_vehicle_detector.dat.bz2:
暫未找到python調(diào)用方法
9. mmod_front_and_rear_end_vehicle_detector.dat.bz2:
暫未找到python調(diào)用方法
10. dnn_gender_classifier_v1.dat.bz2:
暫未找到python調(diào)用方法
11. dnn_age_predictor_v1.dat.bz2:
暫未找到python調(diào)用方法
12. resnet50_1000_imagenet_classifier.dnn.bz2:
暫未找到python調(diào)用方法
13. dcgan_162x162_synth_faces.dnn.bz2:
暫未找到python調(diào)用方法
實(shí)用技巧
眨眼次數(shù)記錄
import dlib
import cv2
import numpy as np# 計(jì)算眼睛長(zhǎng)寬比
def eye_aspect_ratio(eye):A = np.linalg.norm(eye[1] - eye[5])B = np.linalg.norm(eye[2] - eye[4])C = np.linalg.norm(eye[0] - eye[3])ear = (A + B) / (2.0 * C)return ear# 獲取最大的人臉
def largest_face(dets):if len(dets) == 1:return 0face_areas = [(det.right() - det.left()) *(det.bottom() - det.top()) for det in dets]largest_area = face_areas[0]largest_index = 0for index in range(1, len(dets)):if face_areas[index] > largest_area:largest_index = indexlargest_area = face_areas[index]return largest_index# 初始化探測(cè)器和預(yù)測(cè)器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")# 獲取視頻流
cap = cv2.VideoCapture(0)# 初始化幀計(jì)數(shù)器和眨眼計(jì)數(shù)器
frame_counter = 0
blink_counter = 0while True:# 獲取當(dāng)前幀ret, frame = cap.read()if not ret:break# 轉(zhuǎn)換為灰度圖gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# 檢測(cè)人臉faces = detector(gray, 0)# 檢測(cè)到人臉if len(faces) > 0:# 獲取最大的人臉index = largest_face(faces)face = faces[index]# 獲取特征點(diǎn)landmarks = np.matrix([[p.x, p.y] for p in predictor(frame, face).parts()])# 提取左右眼點(diǎn)left_eye = landmarks[42:48]right_eye = landmarks[36:42]# 計(jì)算EARleft_ear = eye_aspect_ratio(left_eye)right_ear = eye_aspect_ratio(right_eye)ear = (left_ear + right_ear) / 2.0# 判斷是否眨眼if ear < 0.21:frame_counter += 1status = "Blinking"else:# 眨眼次數(shù)判斷if frame_counter >= 3:blink_counter += 1frame_counter = 0status = "Open"# 顯示眨眼結(jié)果cv2.putText(frame, "Blinks: {}".format(blink_counter), (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)cv2.putText(frame, "EAR: {:.2f}".format(ear), (300, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)cv2.putText(frame, "Status: {}".format(status), (10, 60),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)# 顯示畫面cv2.imshow("Frame", frame)# 按Q退出key = cv2.waitKey(1) & 0xFFif key == ord('q'):break# 釋放資源并關(guān)閉窗口
cap.release()
cv2.destroyAllWindows()
下一步嘗試
dlib庫(kù)在人臉檢測(cè)和面部landmark定位方面非常強(qiáng)大,主要支持的功能包括:
- 人臉檢測(cè) - 使用CNN模型進(jìn)行快速且準(zhǔn)確的人臉檢測(cè)。
- 人臉關(guān)鍵點(diǎn)定位 - 基于68點(diǎn)或5點(diǎn)模型,定位人臉的關(guān)鍵結(jié)構(gòu)點(diǎn),如眉毛、眼睛、鼻子、嘴巴等。
- 人臉識(shí)別 - 通過(guò)提取人臉特征,實(shí)現(xiàn)面部比對(duì)識(shí)別不同人臉。
- 人臉校準(zhǔn) - 對(duì)人臉圖像進(jìn)行校準(zhǔn),實(shí)現(xiàn)平移、旋轉(zhuǎn)和縮放調(diào)整。
- 頭部姿態(tài)估計(jì) - 通過(guò)面部關(guān)鍵點(diǎn)分析頭部的3D方向和姿態(tài)。
- 微笑檢測(cè) - 通過(guò)觀察嘴巴形狀變化判斷是否微笑。
- 眨眼檢測(cè) - 通過(guò)眼睛形狀分析判斷是否眨眼。
- 情緒識(shí)別 - 利用面部表情判斷人臉情緒,如生氣、高興、悲傷等。
- 年齡/性別預(yù)測(cè) - 基于人臉圖像判斷年齡階段和性別。
- 3D人臉重建 - 通過(guò)2D圖片生成3D人臉模型。
dlib提供了非常方便的人臉?lè)治鯝PI,包括數(shù)據(jù)訓(xùn)練和預(yù)訓(xùn)練模型,是人臉相關(guān)任務(wù)不可多得的強(qiáng)大工具庫(kù)。
shape_predictor_68_face_landmarks.dat 這個(gè)人臉68點(diǎn)標(biāo)志模型不僅可以實(shí)現(xiàn)眨眼檢測(cè),結(jié)合計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)算法,還可以擴(kuò)展實(shí)現(xiàn)更多的面部分析任務(wù):
- 微笑檢測(cè):通過(guò)觀察嘴角上揚(yáng)的關(guān)鍵點(diǎn)坐標(biāo)變化來(lái)判斷是否微笑。
- 情緒識(shí)別:觀察眉毛、眼睛、嘴巴等關(guān)鍵點(diǎn)形變來(lái)判斷面部表達(dá)的情緒。
- 年齡/性別預(yù)測(cè):建立回歸/分類模型,以關(guān)鍵點(diǎn)坐標(biāo)和相對(duì)位置關(guān)系作為特征,預(yù)測(cè)年齡和性別。
- 頭部姿態(tài)分析:根據(jù)關(guān)鍵點(diǎn)構(gòu)成的人臉輪廓變化推斷頭部的三維旋轉(zhuǎn)和平移信息。
- 面部交換:結(jié)合圖片變形,可以在不同人臉之間交換表情。
基于該模型提取的特征非常豐富,可以支持構(gòu)建各種面部理解和分析的機(jī)器學(xué)習(xí)模型。需要注意商業(yè)授權(quán)限制,但對(duì)研究用途非常有價(jià)值。掌握了計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)技巧,可以開(kāi)發(fā)出很多有趣的人臉應(yīng)用。
寫給自己(關(guān)閉gpu加速僅在cpu上加載模型)
根據(jù)的錯(cuò)誤日志,問(wèn)題出在加載RetinaFace模型的時(shí)候:
File "/home/topeet/rknn/RetinaFace-FaceNet/retinaface.py", line 124, in __init__self.generate()
File "/home/topeet/rknn/RetinaFace-FaceNet/retinaface.py", line 146, in generatestate_dict = torch.load(self.retinaface_model_path)
所以需要在retinaface.py里面加載模型的時(shí)候添加map_location參數(shù):
# retinaface.pyimport torchclass RetinaFace():def __init__(self):...def generate(self):...# 原代碼# state_dict = torch.load(self.retinaface_model_path) # 修改為state_dict = torch.load(self.retinaface_model_path, map_location=torch.device('cpu'))
用map_location='cpu’告訴torch將模型加載到CPU上。
這樣應(yīng)該就可以避免CUDA不可用的問(wèn)題了。
另外,為了保證結(jié)果的一致性,在加載模型之前可以加上:
torch.cuda.empty_cache()
清空GPU緩存,torch就會(huì)把 computation 默認(rèn)放在CPU上做。
所以完整的修改代碼是:
import torchclass RetinaFace():def __init__(self):...def generate(self):...torch.cuda.empty_cache() state_dict = torch.load(self.retinaface_model_path, map_location=torch.device('cpu'))
總結(jié)
在國(guó)慶和中秋雙節(jié)的歡慶氛圍中,我深入研究了dlib,并在實(shí)踐中遭遇了種種問(wèn)題。通過(guò)不懈的努力和探索,我成功地克服了挑戰(zhàn),取得了技術(shù)上的突破。這個(gè)過(guò)程不僅讓我更深入地理解了活體檢測(cè)技術(shù)的原理,也鍛煉了我的問(wèn)題解決能力。希望通過(guò)我的分享,能夠?yàn)榇蠹姨峁┮恍┯袃r(jià)值的經(jīng)驗(yàn),也希望在未來(lái)的技術(shù)道路上,我們能夠不斷探索,共同進(jìn)步,這篇文章并未完結(jié),我還會(huì)繼續(xù)堅(jiān)持更新。