1 說(shuō)明:
=====
1.1 吸煙有害健康!!純屬娛樂(lè)和學(xué)習(xí)Python的相關(guān)知識(shí)。
1.2 雖然是娛樂(lè),但是opencv、dlib和python在人工智能、人臉識(shí)別、自動(dòng)化等有很大作用,目前已經(jīng)或者未來(lái)會(huì)有更多的應(yīng)用,作為一名普通人,學(xué)習(xí)一點(diǎn)知識(shí)很有必要。
1.3 我的文章通俗易懂,小白都會(huì),而且親測(cè)過(guò),沒(méi)有編程經(jīng)驗(yàn)的,一看就會(huì)!可以培養(yǎng)自己和孩子的學(xué)習(xí)計(jì)算機(jī)和編程興趣!
1.4 效果圖:
圖片來(lái)源:https://www.wanyx.com/jiaocheng/36683.html
2 準(zhǔn)備工作:
========
2.1 環(huán)境:
華為筆記本電腦、深度deepin-linux操作系統(tǒng)、python3.8和微軟vscode編輯器。
2.2 要求:
2.2.1 PIL、numpy、imutils模塊安裝,安裝簡(jiǎn)單,省略。
2.2.2 cv2模塊安裝:
pip install opencv-python
#下面是我的cv2模塊相關(guān)初步介紹的文章
https://www.toutiao.com/i6833713845005976067/
2.2.3 dlib模塊安裝:有坑!!!
我是這么安裝的,從github下載包,解壓。
https://github.com/davisking/dlib
我是在桌面上,終端打開(kāi),輸入:
python setup.py install #推薦
#下面是我的安裝
#xgj@xgj-PC:~/Desktop/dlib/dlib-master$
sudo python3.8 setup.py install #本機(jī)安裝
3 代碼來(lái)源:
========
3.1 源代碼:
https://github.com/tomoncle/face-detection-induction-course
下載,解壓,找到:
input_video_stream_paste_mask.py,進(jìn)行修改。
3.2
shape_predictor_68_face_landmarks.dat下載
官網(wǎng),網(wǎng)速慢,還有坑,建議下面地址下載。
https://jaist.dl.sourceforge.net/project/dclib/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2
3.3 修改后的代碼:為了簡(jiǎn)潔,刪除不必要的注釋和代碼:
# @Author : tomoncle
# @Site : https://github.com/tomoncle/face-detection-induction-course
#導(dǎo)出模塊
from time import sleep
import cv2
import numpy as np
from PIL import Image
from imutils import face_utils, resize
from dlib import get_frontal_face_detector, shape_predictor
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í)別器
#下載的shape_predictor_68_face_landmarks.dat,解壓放在指定路徑下,因?yàn)槲沂菃?dòng)微軟vscode編輯器
self.predictor = shape_predictor("/home/xgj/Desktop/dlib/xxx/face-detection-induction-course-master/shape_predictor_68_face_landmarks.dat") # 面部分析器
self.fps = 4 # 面具存在時(shí)間基礎(chǔ)時(shí)間
self.animation_time = 0 # 動(dòng)畫周期初始值
self.duration = self.fps * 4 # 動(dòng)畫周期最大值
self.fixed_time = 4 # 畫圖之后,停留時(shí)間
self.max_width = 500 # 圖像大小
self.deal, self.text, self.cigarette = None, None, None # 面具對(duì)象
def read_data(self):
_, data = self.video_capture.read()
return data
def save_data(self, draw_img):
if not self.saved:
return
#指定路徑
draw_img.save("/home/xgj/Desktop/dlib/xxx/face-detection-induction-course-master/images/%05d.png" % self.animation_time)
def init_mask(self):
self.console("加載面具...")
self.deal, self.text, self.cigarette = (
#修改指定路徑,因?yàn)槲沂菃?dòng)微軟vscode編輯器
Image.open(x) for x in ["/home/xgj/Desktop/dlib/xxx/face-detection-induction-course-master/images/deals.png", "/home/xgj/Desktop/dlib/xxx/face-detection-induction-course-master/images/text.png", "/home/xgj/Desktop/dlib/xxx/face-detection-induction-course-master/images/cigarette.png"]
)
def get_glasses_info(self, face_shape, face_width):
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):
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): #人臉定位
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
def start(self):
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 listener_keys(self):
key = cv2.waitKey(1) & 0xFF
#按字母q是退出
if key == ord("q"):
self.listener = False
self.console("程序退出")
sleep(1)
self.exit()
#按字母d是開(kāi)始戴墨鏡和叼煙
if key == ord("d"):
self.doing = not self.doing
def exit(self):
self.video_capture.release()
cv2.destroyAllwindows()
def drawing(self, draw_img, faces):
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)
@classmethod
def console(cls, s):
print("{} !".format(s))
if __name__ == '__main__':
ms = DynamicStreamMaskService()
ms.start()
3.4 效果:
吸煙有害健康!!!哈哈哈
4 小插曲:
=======
4.1 本機(jī)是華為筆記本電腦,預(yù)裝深度deepin-linux操作系統(tǒng),原因眾所周知!使用起來(lái)還是很方便的!
4.2 在我調(diào)用攝像頭時(shí),起初竟然一片漆黑!!于是,我私下“罵了華為”,什么“高科技”筆記本電腦,竟然沒(méi)有安裝攝像頭!!!
4.3 后來(lái)網(wǎng)上一查,還真是高科技,華為牛!攝像頭藏在鍵盤7上面,如下圖,按一下彈出來(lái),牛!
華為威武!中華有為,支持國(guó)產(chǎn)!!
自己整理并分享出來(lái),喜歡的點(diǎn)贊、轉(zhuǎn)發(fā)和收藏。