用Python獲取攝像頭并實(shí)時控制人臉的實(shí)現(xiàn)示例
實(shí)現(xiàn)流程
從攝像頭獲取視頻流,并轉(zhuǎn)換為一幀一幀的圖像,然后將圖像信息傳遞給opencv這個工具庫處理,返回灰度圖像(就像你使用本地靜態(tài)圖片一樣)
程序啟動后,根據(jù)監(jiān)聽器信息,使用一個while循環(huán),不斷的加載視頻圖像,然后返回給opencv工具呈現(xiàn)圖像信息。
創(chuàng)建一個鍵盤事件監(jiān)聽,按下"d"鍵,則開始執(zhí)行面部匹配,并進(jìn)行面具加載(這個過程是動態(tài)的,你可以隨時移動)。
面部匹配使用Dlib中的人臉檢測算法來查看是否有人臉存在。如果有,它將為每個人臉創(chuàng)建一個結(jié)束位置,眼鏡和煙卷會移動到那里結(jié)束。
然后我們需要縮放和旋轉(zhuǎn)我們的眼鏡以適合每個人的臉。我們將使用從Dlib的68點(diǎn)模型返回的點(diǎn)集來找到眼睛和嘴巴的中心,并為它們之間的空間旋轉(zhuǎn)。
在我們實(shí)時獲取眼鏡和煙卷的最終位置后,眼鏡和煙卷從屏幕頂部進(jìn)入,開始匹配你的眼鏡和嘴巴。
假如沒有人臉,程序會直接返回你的視頻信息,不會有面具移動的效果。
默認(rèn)一個周期是4秒鐘。然后你可以通過"d"鍵再次檢測。
程序退出使用"q"鍵。
這里我將這個功能抽象成一個面具加載服務(wù),請跟隨我的代碼一窺究竟吧。
1.導(dǎo)入對應(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ù)類DynamicStreamMaskService及其對應(yīng)的初始化屬性:
class DynamicStreamMaskService(object):
"""
動態(tài)黏貼面具服務(wù)
"""
def __init__(self, saved=False):
self.saved = saved # 是否保存圖片
self.listener = True # 啟動參數(shù)
self.video_capture = cv2.VideoCapture(0) # 調(diào)用本地攝像頭
self.doing = False # 是否進(jìn)行面部面具
self.speed = 0.1 # 面具移動速度
self.detector = get_frontal_face_detector() # 面部識別器
self.predictor = shape_predictor("shape_predictor_68_face_landmarks.dat") # 面部分析器
self.fps = 4 # 面具存在時間基礎(chǔ)時間
self.animation_time = 0 # 動畫周期初始值
self.duration = self.fps * 4 # 動畫周期最大值
self.fixed_time = 4 # 畫圖之后,停留時間
self.max_width = 500 # 圖像大小
self.deal, self.text, self.cigarette = None, None, None # 面具對象
按照上面介紹,我們先實(shí)現(xiàn)讀取視頻流轉(zhuǎn)換圖片的函數(shù):
def read_data(self): """ 從攝像頭獲取視頻流,并轉(zhuǎn)換為一幀一幀的圖像 :return: 返回一幀一幀的圖像信息 """ _, data = self.video_capture.read() return data
接下來我們實(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
剛才我們提到了鍵盤監(jiān)聽事件,這里我們實(shí)現(xiàn)一下這個函數(shù):
def listener_keys(self):
"""
設(shè)置鍵盤監(jiān)聽事件
: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
接下來我們來實(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)了,我們該實(shí)現(xiàn)畫圖函數(shù)了,這個函數(shù)原理和之前我寫的那篇用AI人臉識別技術(shù)實(shí)現(xiàn)抖音特效實(shí)現(xiàn)是一樣的,這里我就不贅述了,可以去github或Python中文社區(qū)微信公眾號查看。
def drawing(self, draw_img, faces):
"""
畫圖
: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)
既然是一個服務(wù)類,那該有啟動與退出函數(shù)吧,最后我們來寫一下吧。
簡單介紹一下這個start()函數(shù), 啟動后根據(jù)初始化監(jiān)聽信息,不斷監(jiān)聽視頻流,并將流信息通過opencv轉(zhuǎn)換成圖像展示出來。
并且調(diào)用按鍵監(jiān)聽函數(shù),不斷的監(jiān)聽你是否按下"d"鍵進(jìn)行面具加載,如果監(jiān)聽成功,則進(jìn)行圖像人臉檢測,并移動面具,
并持續(xù)一個周期的時間結(jié)束,面具此時會根據(jù)你的面部移動而移動。最終呈現(xiàn)文章頂部圖片的效果.
def start(self):
"""
啟動程序
:return:
"""
self.console("程序啟動成功.")
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()
最后,讓我們試試:
if __name__ == '__main__': ms = DynamicStreamMaskService() ms.start()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- OpenCV-Python 攝像頭實(shí)時檢測人臉代碼實(shí)例
- Python3利用Dlib實(shí)現(xiàn)攝像頭實(shí)時人臉檢測和平鋪顯示示例
- python版opencv攝像頭人臉實(shí)時檢測方法
- Python+OpenCV圖像處理——打印圖片屬性、設(shè)置存儲路徑、調(diào)用攝像頭
- 教你如何用python操作攝像頭以及對視頻流的處理
- python使用opencv在Windows下調(diào)用攝像頭實(shí)現(xiàn)解析
- 樹莓派4B+opencv4+python 打開攝像頭的實(shí)現(xiàn)方法
- python實(shí)現(xiàn)從本地攝像頭和網(wǎng)絡(luò)攝像頭截取圖片功能
- python opencv捕獲攝像頭并顯示內(nèi)容的實(shí)現(xiàn)
- python 實(shí)時調(diào)取攝像頭的示例代碼
相關(guān)文章
Python3.7 讀取音頻根據(jù)文件名生成腳本的代碼
這篇文章主要介紹了Python3.7 讀取音頻根據(jù)文件名生成字幕腳本的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
Pandas實(shí)現(xiàn)解析JSON數(shù)據(jù)與導(dǎo)出的示例詳解
其實(shí)使用pandas解析JSON?Dataset要方便得多,所以這篇文章主要為大家介紹了Pandas實(shí)現(xiàn)解析JSON數(shù)據(jù)與導(dǎo)出的具體方法,需要的小伙伴可以收藏一下2023-07-07
pandas去重復(fù)行并分類匯總的實(shí)現(xiàn)方法
這篇文章主要介紹了pandas去重復(fù)行并分類匯總的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
Python3爬取英雄聯(lián)盟英雄皮膚大圖實(shí)例代碼
這篇文章主要介紹了Python3爬取英雄聯(lián)盟英雄皮膚大圖的實(shí)例代碼,文中較詳細(xì)的給大家介紹了爬蟲思路及完整代碼,需要的朋友可以參考下2018-11-11

