Python3利用Dlib實(shí)現(xiàn)攝像頭實(shí)時(shí)人臉檢測(cè)和平鋪顯示示例
1. 引言
在某些場(chǎng)景下,我們不僅需要進(jìn)行實(shí)時(shí)人臉檢測(cè)追蹤,還要進(jìn)行再加工;這里進(jìn)行攝像頭實(shí)時(shí)人臉檢測(cè),并對(duì)于實(shí)時(shí)檢測(cè)的人臉進(jìn)行初步提取;
單個(gè)/多個(gè)人臉檢測(cè),并依次在攝像頭窗口,實(shí)時(shí)平鋪顯示檢測(cè)到的人臉;

圖 1 動(dòng)態(tài)實(shí)時(shí)檢測(cè)效果圖
檢測(cè)到的人臉矩形圖像,會(huì)依次平鋪顯示在攝像頭的左上方;
當(dāng)多個(gè)人臉時(shí)候,也能夠依次鋪開(kāi)顯示;
左上角窗口的大小會(huì)根據(jù)捕獲到的人臉大小實(shí)時(shí)變化;

圖 2 單個(gè)/多個(gè)人臉情況下攝像頭識(shí)別顯示結(jié)果
2. 代碼實(shí)現(xiàn)
主要分為三個(gè)部分:
攝像頭調(diào)用,利用 OpenCv 里面的cv2.VideoCapture();
人臉檢測(cè),這里利用開(kāi)源的 Dlib 框架,Dlib 中人臉檢測(cè)具體可以參考Python 3 利用 Dlib 19.7 進(jìn)行人臉檢測(cè);
圖像填充,剪切部分可以參考Python 3 利用 Dlib 實(shí)現(xiàn)人臉檢測(cè)和剪切;
2.1 攝像頭調(diào)用
Python 中利用 OpenCv 調(diào)用攝像頭的一個(gè)例子how_to_use_camera.py:
# OpenCv 調(diào)用攝像頭
# 默認(rèn)調(diào)用筆記本攝像頭
# Author: coneypo
# Blog: http://www.cnblogs.com/AdaminXie
# GitHub: https://github.com/coneypo/Dlib_face_cut
# Mail: coneypo@foxmail.com
import cv2
cap = cv2.VideoCapture(0)
# cap.set(propId, value)
# 設(shè)置視頻參數(shù): propId - 設(shè)置的視頻參數(shù), value - 設(shè)置的參數(shù)值
cap.set(3, 480)
# cap.isOpened() 返回 true/false, 檢查攝像頭初始化是否成功
print(cap.isOpened())
# cap.read()
"""
返回兩個(gè)值
先返回一個(gè)布爾值, 如果視頻讀取正確, 則為 True, 如果錯(cuò)誤, 則為 False;
也可用來(lái)判斷是否到視頻末尾;
再返回一個(gè)值, 為每一幀的圖像, 該值是一個(gè)三維矩陣;
通用接收方法為:
ret,frame = cap.read();
ret: 布爾值;
frame: 圖像的三維矩陣;
這樣 ret 存儲(chǔ)布爾值, frame 存儲(chǔ)圖像;
若使用一個(gè)變量來(lái)接收兩個(gè)值, 如:
frame = cap.read()
則 frame 為一個(gè)元組, 原來(lái)使用 frame 處需更改為 frame[1]
"""
while cap.isOpened():
ret_flag, img_camera = cap.read()
cv2.imshow("camera", img_camera)
# 每幀數(shù)據(jù)延時(shí) 1ms, 延時(shí)為0, 讀取的是靜態(tài)幀
k = cv2.waitKey(1)
# 按下 's' 保存截圖
if k == ord('s'):
cv2.imwrite("test.jpg", img_camera)
# 按下 'q' 退出
if k == ord('q'):
break
# 釋放所有攝像頭
cap.release()
# 刪除建立的所有窗口
cv2.destroyAllWindows()
2.2 人臉檢測(cè)
利用 Dlib 正向人臉檢測(cè)器,dlib.get_frontal_face_detector();
對(duì)于本地人臉圖像文件,一個(gè)利用 Dlib 進(jìn)行人臉檢測(cè)的例子:
face_detector_v2_use_opencv.py:
# created at 2017-11-27
# updated at 2018-09-06
# Author: coneypo
# Dlib: http://dlib.net/
# Blog: http://www.cnblogs.com/AdaminXie/
# Github: https://github.com/coneypo/Dlib_examples
# create object of OpenCv
# use OpenCv to read and show images
import dlib
import cv2
# 使用 Dlib 的正面人臉檢測(cè)器 frontal_face_detector
detector = dlib.get_frontal_face_detector()
# 圖片所在路徑
# read image
img = cv2.imread("imgs/faces_2.jpeg")
# 使用 detector 檢測(cè)器來(lái)檢測(cè)圖像中的人臉
# use detector of Dlib to detector faces
faces = detector(img, 1)
print("人臉數(shù) / Faces in all: ", len(faces))
# Traversal every face
for i, d in enumerate(faces):
print("第", i+1, "個(gè)人臉的矩形框坐標(biāo):",
"left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
cv2.namedWindow("img", 2)
cv2.imshow("img", img)
cv2.waitKey(0)

圖 3 參數(shù) d.top(), d.right(), d.left(), d.bottom() 位置坐標(biāo)說(shuō)明
2.3 圖像裁剪
如果想訪(fǎng)問(wèn)圖像的某點(diǎn)像素,對(duì)于 opencv 對(duì)象可以利用索引 img [height] [width]:
存儲(chǔ)像素其實(shí)是一個(gè)三維數(shù)組,先高度 height,然后寬度 width;
返回的是一個(gè)顏色數(shù)組(0-255,0-255,0-255),按照(B,G,R)的順序;
比如藍(lán)色就是(255,0,0),紅色是(0,0,255);
所以要做的就是對(duì)于檢測(cè)到的人臉,要依次平鋪填充到攝像頭顯示的實(shí)時(shí)幀 img_rd 中;
所以進(jìn)行圖像裁剪填充這塊的代碼如下(注意要防止截切平鋪的圖像不能超出 640x480 ):
# 檢測(cè)到人臉
if len(faces) != 0:
# 記錄每次開(kāi)始寫(xiě)入人臉像素的寬度位置
faces_start_width = 0
for face in faces:
# 繪制矩形框
cv2.rectangle(img_rd, tuple([face.left(), face.top()]), tuple([face.right(), face.bottom()]),
(0, 255, 255), 2)
height = face.bottom() - face.top()
width = face.right() - face.left()
### 進(jìn)行人臉裁減 ###
# 如果沒(méi)有超出攝像頭邊界
if (face.bottom() < 480) and (face.right() < 640) and \
((face.top() + height) < 480) and ((face.left() + width) < 640):
# 填充
for i in range(height):
for j in range(width):
img_rd[i][faces_start_width + j] = \
img_rd[face.top() + i][face.left() + j]
# 更新 faces_start_width 的坐標(biāo)
faces_start_width += width
記得要更新faces_start_width的坐標(biāo),達(dá)到依次平鋪的效果:

圖 4 平鋪顯示的人臉
2.4. 完整源碼
# 調(diào)用攝像頭實(shí)時(shí)單個(gè)/多個(gè)人臉檢測(cè),并依次在攝像頭窗口,實(shí)時(shí)平鋪顯示檢測(cè)到的人臉;
# Author: coneypo
# Blog: http://www.cnblogs.com/AdaminXie
# GitHub: https://github.com/coneypo/Dlib_face_cut
import dlib
import cv2
import time
# 儲(chǔ)存截圖的目錄
path_screenshots = "data/images/screenshots/"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('data/dlib/shape_predictor_68_face_landmarks.dat')
# 創(chuàng)建 cv2 攝像頭對(duì)象
cap = cv2.VideoCapture(0)
# 設(shè)置視頻參數(shù),propId 設(shè)置的視頻參數(shù),value 設(shè)置的參數(shù)值
cap.set(3, 960)
# 截圖 screenshots 的計(jì)數(shù)器
ss_cnt = 0
while cap.isOpened():
flag, img_rd = cap.read()
# 每幀數(shù)據(jù)延時(shí) 1ms,延時(shí)為 0 讀取的是靜態(tài)幀
k = cv2.waitKey(1)
# 取灰度
img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)
# 人臉數(shù)
faces = detector(img_gray, 0)
# 待會(huì)要寫(xiě)的字體
font = cv2.FONT_HERSHEY_SIMPLEX
# 按下 'q' 鍵退出
if k == ord('q'):
break
else:
# 檢測(cè)到人臉
if len(faces) != 0:
# 記錄每次開(kāi)始寫(xiě)入人臉像素的寬度位置
faces_start_width = 0
for face in faces:
# 繪制矩形框
cv2.rectangle(img_rd, tuple([face.left(), face.top()]), tuple([face.right(), face.bottom()]),
(0, 255, 255), 2)
height = face.bottom() - face.top()
width = face.right() - face.left()
### 進(jìn)行人臉裁減 ###
# 如果沒(méi)有超出攝像頭邊界
if (face.bottom() < 480) and (face.right() < 640) and \
((face.top() + height) < 480) and ((face.left() + width) < 640):
# 填充
for i in range(height):
for j in range(width):
img_rd[i][faces_start_width + j] = \
img_rd[face.top() + i][face.left() + j]
# 更新 faces_start_width 的坐標(biāo)
faces_start_width += width
cv2.putText(img_rd, "Faces in all: " + str(len(faces)), (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
else:
# 沒(méi)有檢測(cè)到人臉
cv2.putText(img_rd, "no face", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
# 添加說(shuō)明
img_rd = cv2.putText(img_rd, "Press 'S': Screen shot", (20, 400), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
img_rd = cv2.putText(img_rd, "Press 'Q': Quit", (20, 450), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
# 按下 's' 鍵保存
if k == ord('s'):
ss_cnt += 1
print(path_screenshots + "screenshot" + "_" + str(ss_cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
time.localtime()) + ".jpg")
cv2.imwrite(path_screenshots + "screenshot" + "_" + str(ss_cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
time.localtime()) + ".jpg",
img_rd)
cv2.namedWindow("camera", 1)
cv2.imshow("camera", img_rd)
# 釋放攝像頭
cap.release()
# 刪除建立的窗口
cv2.destroyAllWindows()
這個(gè)代碼就是把之前做的人臉檢測(cè),圖像拼接幾個(gè)結(jié)合起來(lái),代碼量也很少,只有100行,如有問(wèn)題可以參考之前博客:
Python 3 利用 Dlib 進(jìn)行人臉檢測(cè)
Python 3 利用 Dlib 實(shí)現(xiàn)人臉檢測(cè)和剪切
人臉檢測(cè)對(duì)于機(jī)器性能占用不高,但是如果要進(jìn)行實(shí)時(shí)的圖像裁剪拼接,計(jì)算量可能比較大,所以可能會(huì)出現(xiàn)卡頓;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中關(guān)于print和return的區(qū)別
這篇文章主要介紹了Python中關(guān)于print和return的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
詳解Python是如何實(shí)現(xiàn)issubclass的
這篇文章主要介紹了詳解Python是如何實(shí)現(xiàn)issubclass的,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Python離線(xiàn)安裝各種庫(kù)及pip的方法
這篇文章主要介紹了Python離線(xiàn)安裝各種庫(kù)及pip的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
Python+Pyqt實(shí)現(xiàn)簡(jiǎn)單GUI電子時(shí)鐘
這篇文章主要為大家詳細(xì)介紹了Python+Pyqt實(shí)現(xiàn)簡(jiǎn)單GUI電子時(shí)鐘,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
Python使用turtle繪制有趣的龍年祝福動(dòng)畫(huà)
這篇文章主要介紹了Python的內(nèi)置庫(kù)——小海龜(turtle),它是一個(gè)非常實(shí)用的繪畫(huà)工具,不僅可以幫助我們繪制圖形,還能讓我們查看整個(gè)繪畫(huà)過(guò)程,下面我們就來(lái)看看如何使用turtle繪制有趣的龍年祝福動(dòng)畫(huà)吧2024-01-01

