Python3利用Dlib實現(xiàn)攝像頭實時人臉檢測和平鋪顯示示例
1. 引言
在某些場景下,我們不僅需要進(jìn)行實時人臉檢測追蹤,還要進(jìn)行再加工;這里進(jìn)行攝像頭實時人臉檢測,并對于實時檢測的人臉進(jìn)行初步提取;
單個/多個人臉檢測,并依次在攝像頭窗口,實時平鋪顯示檢測到的人臉;
圖 1 動態(tài)實時檢測效果圖
檢測到的人臉矩形圖像,會依次平鋪顯示在攝像頭的左上方;
當(dāng)多個人臉時候,也能夠依次鋪開顯示;
左上角窗口的大小會根據(jù)捕獲到的人臉大小實時變化;
圖 2 單個/多個人臉情況下攝像頭識別顯示結(jié)果
2. 代碼實現(xiàn)
主要分為三個部分:
攝像頭調(diào)用,利用 OpenCv 里面的cv2.VideoCapture();
人臉檢測,這里利用開源的 Dlib 框架,Dlib 中人臉檢測具體可以參考Python 3 利用 Dlib 19.7 進(jìn)行人臉檢測;
圖像填充,剪切部分可以參考Python 3 利用 Dlib 實現(xiàn)人臉檢測和剪切;
2.1 攝像頭調(diào)用
Python 中利用 OpenCv 調(diào)用攝像頭的一個例子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() """ 返回兩個值 先返回一個布爾值, 如果視頻讀取正確, 則為 True, 如果錯誤, 則為 False; 也可用來判斷是否到視頻末尾; 再返回一個值, 為每一幀的圖像, 該值是一個三維矩陣; 通用接收方法為: ret,frame = cap.read(); ret: 布爾值; frame: 圖像的三維矩陣; 這樣 ret 存儲布爾值, frame 存儲圖像; 若使用一個變量來接收兩個值, 如: frame = cap.read() 則 frame 為一個元組, 原來使用 frame 處需更改為 frame[1] """ while cap.isOpened(): ret_flag, img_camera = cap.read() cv2.imshow("camera", img_camera) # 每幀數(shù)據(jù)延時 1ms, 延時為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 人臉檢測
利用 Dlib 正向人臉檢測器,dlib.get_frontal_face_detector();
對于本地人臉圖像文件,一個利用 Dlib 進(jìn)行人臉檢測的例子:
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 的正面人臉檢測器 frontal_face_detector detector = dlib.get_frontal_face_detector() # 圖片所在路徑 # read image img = cv2.imread("imgs/faces_2.jpeg") # 使用 detector 檢測器來檢測圖像中的人臉 # 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, "個人臉的矩形框坐標(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)說明
2.3 圖像裁剪
如果想訪問圖像的某點像素,對于 opencv 對象可以利用索引 img [height] [width]:
存儲像素其實是一個三維數(shù)組,先高度 height,然后寬度 width;
返回的是一個顏色數(shù)組(0-255,0-255,0-255),按照(B,G,R)的順序;
比如藍(lán)色就是(255,0,0),紅色是(0,0,255);
所以要做的就是對于檢測到的人臉,要依次平鋪填充到攝像頭顯示的實時幀 img_rd 中;
所以進(jìn)行圖像裁剪填充這塊的代碼如下(注意要防止截切平鋪的圖像不能超出 640x480 ):
# 檢測到人臉 if len(faces) != 0: # 記錄每次開始寫入人臉像素的寬度位置 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)行人臉裁減 ### # 如果沒有超出攝像頭邊界 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)用攝像頭實時單個/多個人臉檢測,并依次在攝像頭窗口,實時平鋪顯示檢測到的人臉; # Author: coneypo # Blog: http://www.cnblogs.com/AdaminXie # GitHub: https://github.com/coneypo/Dlib_face_cut import dlib import cv2 import time # 儲存截圖的目錄 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 攝像頭對象 cap = cv2.VideoCapture(0) # 設(shè)置視頻參數(shù),propId 設(shè)置的視頻參數(shù),value 設(shè)置的參數(shù)值 cap.set(3, 960) # 截圖 screenshots 的計數(shù)器 ss_cnt = 0 while cap.isOpened(): flag, img_rd = cap.read() # 每幀數(shù)據(jù)延時 1ms,延時為 0 讀取的是靜態(tài)幀 k = cv2.waitKey(1) # 取灰度 img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY) # 人臉數(shù) faces = detector(img_gray, 0) # 待會要寫的字體 font = cv2.FONT_HERSHEY_SIMPLEX # 按下 'q' 鍵退出 if k == ord('q'): break else: # 檢測到人臉 if len(faces) != 0: # 記錄每次開始寫入人臉像素的寬度位置 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)行人臉裁減 ### # 如果沒有超出攝像頭邊界 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: # 沒有檢測到人臉 cv2.putText(img_rd, "no face", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA) # 添加說明 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()
這個代碼就是把之前做的人臉檢測,圖像拼接幾個結(jié)合起來,代碼量也很少,只有100行,如有問題可以參考之前博客:
Python 3 利用 Dlib 實現(xiàn)人臉檢測和剪切
人臉檢測對于機器性能占用不高,但是如果要進(jìn)行實時的圖像裁剪拼接,計算量可能比較大,所以可能會出現(xiàn)卡頓;
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python多進(jìn)程并發(fā)(multiprocessing)用法實例詳解
這篇文章主要介紹了Python多進(jìn)程并發(fā)(multiprocessing)用法,實例分析了multiprocessing模塊進(jìn)程操作的相關(guān)技巧,需要的朋友可以參考下2015-06-06Pycharm中SSH、SFTP連接遠(yuǎn)程服務(wù)器編輯調(diào)試實例
這篇文章主要介紹了Pycharm中SSH、SFTP連接遠(yuǎn)程服務(wù)器編輯調(diào)試實例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06python輸出當(dāng)前目錄下index.html文件路徑的方法
這篇文章主要介紹了python輸出當(dāng)前目錄下index.html文件路徑的方法,涉及Python操作目錄的相關(guān)技巧,需要的朋友可以參考下2015-04-04Jupyter導(dǎo)入自定義模塊及導(dǎo)入后TypeError錯誤問題及解決
這篇文章主要介紹了Jupyter導(dǎo)入自定義模塊及導(dǎo)入后TypeError錯誤問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01使用Python實現(xiàn)文本英文統(tǒng)計功能
這篇文章主要為大家詳細(xì)介紹了如何使用Python來實現(xiàn)文本英文統(tǒng)計,包括單詞頻率統(tǒng)計、詞匯量統(tǒng)計以及文本情感分析等,感興趣的小伙伴可以參考下2024-05-05