用Python獲取攝像頭并實(shí)時(shí)控制人臉的實(shí)現(xiàn)示例
實(shí)現(xiàn)流程
從攝像頭獲取視頻流,并轉(zhuǎn)換為一幀一幀的圖像,然后將圖像信息傳遞給opencv這個(gè)工具庫(kù)處理,返回灰度圖像(就像你使用本地靜態(tài)圖片一樣)
程序啟動(dòng)后,根據(jù)監(jiān)聽(tīng)器信息,使用一個(gè)while循環(huán),不斷的加載視頻圖像,然后返回給opencv工具呈現(xiàn)圖像信息。
創(chuàng)建一個(gè)鍵盤(pán)事件監(jiān)聽(tīng),按下"d"鍵,則開(kāi)始執(zhí)行面部匹配,并進(jìn)行面具加載(這個(gè)過(guò)程是動(dòng)態(tài)的,你可以隨時(shí)移動(dòng))。
面部匹配使用Dlib中的人臉檢測(cè)算法來(lái)查看是否有人臉存在。如果有,它將為每個(gè)人臉創(chuàng)建一個(gè)結(jié)束位置,眼鏡和煙卷會(huì)移動(dòng)到那里結(jié)束。
然后我們需要縮放和旋轉(zhuǎn)我們的眼鏡以適合每個(gè)人的臉。我們將使用從Dlib的68點(diǎn)模型返回的點(diǎn)集來(lái)找到眼睛和嘴巴的中心,并為它們之間的空間旋轉(zhuǎn)。
在我們實(shí)時(shí)獲取眼鏡和煙卷的最終位置后,眼鏡和煙卷從屏幕頂部進(jìn)入,開(kāi)始匹配你的眼鏡和嘴巴。
假如沒(méi)有人臉,程序會(huì)直接返回你的視頻信息,不會(huì)有面具移動(dòng)的效果。
默認(rèn)一個(gè)周期是4秒鐘。然后你可以通過(guò)"d"鍵再次檢測(cè)。
程序退出使用"q"鍵。
這里我將這個(gè)功能抽象成一個(gè)面具加載服務(wù),請(qǐng)跟隨我的代碼一窺究竟吧。
1.導(dǎo)入對(duì)應(yīng)的工具包
from time import sleep import cv2 import numpy as np from PIL import Image from imutils import face_utils, resize try: from dlib import get_frontal_face_detector, shape_predictor except ImportError: raise
創(chuàng)建面具加載服務(wù)類(lèi)DynamicStreamMaskService及其對(duì)應(yīng)的初始化屬性:
class DynamicStreamMaskService(object): """ 動(dòng)態(tài)黏貼面具服務(wù) """ def __init__(self, saved=False): self.saved = saved # 是否保存圖片 self.listener = True # 啟動(dòng)參數(shù) self.video_capture = cv2.VideoCapture(0) # 調(diào)用本地?cái)z像頭 self.doing = False # 是否進(jìn)行面部面具 self.speed = 0.1 # 面具移動(dòng)速度 self.detector = get_frontal_face_detector() # 面部識(shí)別器 self.predictor = shape_predictor("shape_predictor_68_face_landmarks.dat") # 面部分析器 self.fps = 4 # 面具存在時(shí)間基礎(chǔ)時(shí)間 self.animation_time = 0 # 動(dòng)畫(huà)周期初始值 self.duration = self.fps * 4 # 動(dòng)畫(huà)周期最大值 self.fixed_time = 4 # 畫(huà)圖之后,停留時(shí)間 self.max_width = 500 # 圖像大小 self.deal, self.text, self.cigarette = None, None, None # 面具對(duì)象
按照上面介紹,我們先實(shí)現(xiàn)讀取視頻流轉(zhuǎn)換圖片的函數(shù):
def read_data(self): """ 從攝像頭獲取視頻流,并轉(zhuǎn)換為一幀一幀的圖像 :return: 返回一幀一幀的圖像信息 """ _, data = self.video_capture.read() return data
接下來(lái)我們實(shí)現(xiàn)人臉定位函數(shù),及眼鏡和煙卷的定位:
def get_glasses_info(self, face_shape, face_width): """ 獲取當(dāng)前面部的眼鏡信息 :param face_shape: :param face_width: :return: """ left_eye = face_shape[36:42] right_eye = face_shape[42:48] left_eye_center = left_eye.mean(axis=0).astype("int") right_eye_center = right_eye.mean(axis=0).astype("int") y = left_eye_center[1] - right_eye_center[1] x = left_eye_center[0] - right_eye_center[0] eye_angle = np.rad2deg(np.arctan2(y, x)) deal = self.deal.resize( (face_width, int(face_width * self.deal.size[1] / self.deal.size[0])), resample=Image.LANCZOS) deal = deal.rotate(eye_angle, expand=True) deal = deal.transpose(Image.FLIP_TOP_BOTTOM) left_eye_x = left_eye[0, 0] - face_width // 4 left_eye_y = left_eye[0, 1] - face_width // 6 return {"image": deal, "pos": (left_eye_x, left_eye_y)} def get_cigarette_info(self, face_shape, face_width): """ 獲取當(dāng)前面部的煙卷信息 :param face_shape: :param face_width: :return: """ mouth = face_shape[49:68] mouth_center = mouth.mean(axis=0).astype("int") cigarette = self.cigarette.resize( (face_width, int(face_width * self.cigarette.size[1] / self.cigarette.size[0])), resample=Image.LANCZOS) x = mouth[0, 0] - face_width + int(16 * face_width / self.cigarette.size[0]) y = mouth_center[1] return {"image": cigarette, "pos": (x, y)} def orientation(self, rects, img_gray): """ 人臉定位 :return: """ faces = [] for rect in rects: face = {} face_shades_width = rect.right() - rect.left() predictor_shape = self.predictor(img_gray, rect) face_shape = face_utils.shape_to_np(predictor_shape) face['cigarette'] = self.get_cigarette_info(face_shape, face_shades_width) face['glasses'] = self.get_glasses_info(face_shape, face_shades_width) faces.append(face) return faces
剛才我們提到了鍵盤(pán)監(jiān)聽(tīng)事件,這里我們實(shí)現(xiàn)一下這個(gè)函數(shù):
def listener_keys(self): """ 設(shè)置鍵盤(pán)監(jiān)聽(tīng)事件 :return: """ key = cv2.waitKey(1) & 0xFF if key == ord("q"): self.listener = False self.console("程序退出") sleep(1) self.exit() if key == ord("d"): self.doing = not self.doing
接下來(lái)我們來(lái)實(shí)現(xiàn)加載面具信息的函數(shù):
def init_mask(self): """ 加載面具 :return: """ self.console("加載面具...") self.deal, self.text, self.cigarette = ( Image.open(x) for x in ["images/deals.png", "images/text.png", "images/cigarette.png"] )
上面基本的功能都實(shí)現(xiàn)了,我們?cè)搶?shí)現(xiàn)畫(huà)圖函數(shù)了,這個(gè)函數(shù)原理和之前我寫(xiě)的那篇用AI人臉識(shí)別技術(shù)實(shí)現(xiàn)抖音特效實(shí)現(xiàn)是一樣的,這里我就不贅述了,可以去github或Python中文社區(qū)微信公眾號(hào)查看。
def drawing(self, draw_img, faces): """ 畫(huà)圖 :param draw_img: :param faces: :return: """ for face in faces: if self.animation_time < self.duration - self.fixed_time: current_x = int(face["glasses"]["pos"][0]) current_y = int(face["glasses"]["pos"][1] * self.animation_time / (self.duration - self.fixed_time)) draw_img.paste(face["glasses"]["image"], (current_x, current_y), face["glasses"]["image"]) cigarette_x = int(face["cigarette"]["pos"][0]) cigarette_y = int(face["cigarette"]["pos"][1] * self.animation_time / (self.duration - self.fixed_time)) draw_img.paste(face["cigarette"]["image"], (cigarette_x, cigarette_y), face["cigarette"]["image"]) else: draw_img.paste(face["glasses"]["image"], face["glasses"]["pos"], face["glasses"]["image"]) draw_img.paste(face["cigarette"]["image"], face["cigarette"]["pos"], face["cigarette"]["image"]) draw_img.paste(self.text, (75, draw_img.height // 2 + 128), self.text)
既然是一個(gè)服務(wù)類(lèi),那該有啟動(dòng)與退出函數(shù)吧,最后我們來(lái)寫(xiě)一下吧。
簡(jiǎn)單介紹一下這個(gè)start()函數(shù), 啟動(dòng)后根據(jù)初始化監(jiān)聽(tīng)信息,不斷監(jiān)聽(tīng)視頻流,并將流信息通過(guò)opencv轉(zhuǎn)換成圖像展示出來(lái)。
并且調(diào)用按鍵監(jiān)聽(tīng)函數(shù),不斷的監(jiān)聽(tīng)你是否按下"d"鍵進(jìn)行面具加載,如果監(jiān)聽(tīng)成功,則進(jìn)行圖像人臉檢測(cè),并移動(dòng)面具,
并持續(xù)一個(gè)周期的時(shí)間結(jié)束,面具此時(shí)會(huì)根據(jù)你的面部移動(dòng)而移動(dòng)。最終呈現(xiàn)文章頂部圖片的效果.
def start(self): """ 啟動(dòng)程序 :return: """ self.console("程序啟動(dòng)成功.") self.init_mask() while self.listener: frame = self.read_data() frame = resize(frame, width=self.max_width) img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) rects = self.detector(img_gray, 0) faces = self.orientation(rects, img_gray) draw_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) if self.doing: self.drawing(draw_img, faces) self.animation_time += self.speed self.save_data(draw_img) if self.animation_time > self.duration: self.doing = False self.animation_time = 0 else: frame = cv2.cvtColor(np.asarray(draw_img), cv2.COLOR_RGB2BGR) cv2.imshow("hello mask", frame) self.listener_keys() def exit(self): """ 程序退出 :return: """ self.video_capture.release() cv2.destroyAllWindows()
最后,讓我們?cè)囋嚕?/p>
if __name__ == '__main__': ms = DynamicStreamMaskService() ms.start()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- OpenCV-Python 攝像頭實(shí)時(shí)檢測(cè)人臉代碼實(shí)例
- Python3利用Dlib實(shí)現(xiàn)攝像頭實(shí)時(shí)人臉檢測(cè)和平鋪顯示示例
- python版opencv攝像頭人臉實(shí)時(shí)檢測(cè)方法
- Python+OpenCV圖像處理——打印圖片屬性、設(shè)置存儲(chǔ)路徑、調(diào)用攝像頭
- 教你如何用python操作攝像頭以及對(duì)視頻流的處理
- python使用opencv在Windows下調(diào)用攝像頭實(shí)現(xiàn)解析
- 樹(shù)莓派4B+opencv4+python 打開(kāi)攝像頭的實(shí)現(xiàn)方法
- python實(shí)現(xiàn)從本地?cái)z像頭和網(wǎng)絡(luò)攝像頭截取圖片功能
- python opencv捕獲攝像頭并顯示內(nèi)容的實(shí)現(xiàn)
- python 實(shí)時(shí)調(diào)取攝像頭的示例代碼
相關(guān)文章
pycharm編寫(xiě)spark程序,導(dǎo)入pyspark包的3中實(shí)現(xiàn)方法
這篇文章主要介紹了pycharm編寫(xiě)spark程序,導(dǎo)入pyspark包的3中實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08Python實(shí)現(xiàn)二叉樹(shù)的最小深度的兩種方法
這篇文章主要介紹了Python實(shí)現(xiàn)二叉樹(shù)的最小深度的兩種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09python 日志模塊 日志等級(jí)設(shè)置失效的解決方案
這篇文章主要介紹了python 日志模塊 日志等級(jí)設(shè)置失效的問(wèn)題及解決方案,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05使用Python機(jī)器學(xué)習(xí)降低靜態(tài)日志噪聲
今天小編就為大家分享一篇關(guān)于使用Python和機(jī)器學(xué)習(xí)的靜態(tài)日志噪聲的文章,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-09-09python pytorch中.view()函數(shù)的用法解讀
這篇文章主要介紹了python pytorch中.view()函數(shù)的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08Python使用pyenv實(shí)現(xiàn)多環(huán)境管理
這篇文章主要介紹了Python使用pyenv實(shí)現(xiàn)多環(huán)境管理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02解決TensorFlow訓(xùn)練模型及保存數(shù)量限制的問(wèn)題
這篇文章主要介紹了解決TensorFlow訓(xùn)練模型及保存數(shù)量限制的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03