隨著圣誕的到來,想給給自己的頭像加上一頂圣誕帽。如果不是頭像铐殃,就加一個(gè)圣誕老人陪伴。
用Python給頭像加上圣誕帽砍聊,看了下大概也都是來自2017年大神的文章:https://zhuanlan.zhihu.com/p/32283641
主要流程
素材準(zhǔn)備
人臉檢測(cè)與人臉關(guān)鍵點(diǎn)檢測(cè)
調(diào)整大小背稼,添加帽子
用dlib的正臉檢測(cè)器進(jìn)行人臉檢測(cè)贰军,用dlib提供的模型提取人臉的五個(gè)關(guān)鍵點(diǎn)
# dlib人臉關(guān)鍵點(diǎn)檢測(cè)器
predictor_path = "shape_predictor_5_face_landmarks.dat"
predictor = dlib.shape_predictor(predictor_path)
# dlib正臉檢測(cè)器
detector = dlib.get_frontal_face_detector()
# 正臉檢測(cè)
dets = detector(img, 1)
# 如果檢測(cè)到人臉
if len(dets)>0:
for d in dets:
x,y,w,h = d.left(),d.top(), d.right()-d.left(), d.bottom()-d.top()
# x,y,w,h = faceRect
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2,8,0)
# 關(guān)鍵點(diǎn)檢測(cè)玻蝌,5個(gè)關(guān)鍵點(diǎn)
shape = predictor(img, d)
for point in shape.parts():
cv2.circle(img,(point.x,point.y),3,color=(0,255,0))
cv2.imshow("image",img)
cv2.waitKey()
調(diào)整帽子大小,帶帽
選取兩個(gè)眼角的點(diǎn)词疼,求中心作為放置帽子的x方向的參考坐標(biāo)俯树,y方向的坐標(biāo)用人臉框上線的y坐標(biāo)表示。然后我們根據(jù)人臉檢測(cè)得到的人臉的大小調(diào)整帽子的大小贰盗,使得帽子大小合適许饿。
# 選取左右眼眼角的點(diǎn)
point1 = shape.part(0)
point2 = shape.part(2)
# 求兩點(diǎn)中心
eyes_center = ((point1.x+point2.x)//2,(point1.y+point2.y)//2)
# cv2.circle(img,eyes_center,3,color=(0,255,0))
# cv2.imshow("image",img)
# cv2.waitKey()
# 根據(jù)人臉大小調(diào)整帽子大小
factor = 1.5
resized_hat_h = int(round(rgb_hat.shape[0]*w/rgb_hat.shape[1]*factor))
resized_hat_w = int(round(rgb_hat.shape[1]*w/rgb_hat.shape[1]*factor))
if resized_hat_h > y:
resized_hat_h = y-1
# 根據(jù)人臉大小調(diào)整帽子大小
resized_hat = cv2.resize(rgb_hat,(resized_hat_w,resized_hat_h))
添加小圖標(biāo)
當(dāng)然有些同學(xué)的頭像不是人物或不能準(zhǔn)確的識(shí)別無關(guān),所有添加了標(biāo)識(shí)舵盈。(即在右下添加小圖標(biāo))陋率。
小圖標(biāo)避免單調(diào),是從圖標(biāo)中隨機(jī)選擇一個(gè):
圖標(biāo)位置也可以根據(jù)愛好調(diào)整大小和位置
layer.paste(logo, (img.size[0] - logo.size[0], img.size[1]-logo.size[1]))
代碼如下:
# 水印圖片
num = random.randint(1, 5)
logo = Image.open("img_icon/santa_" + str(num) + ".png")
img = Image.open(imgPath)
print(img.size, logo.size)
# 圖層
layer = Image.new("RGBA", img.size, (255, 255, 255, 0))
layer.paste(logo, (img.size[0] - logo.size[0], img.size[1]-logo.size[1]))
# 覆蓋
img_after = Image.composite(layer, img, layer)
# img_after.show()
img_after.save(outImgePath)
結(jié)果如下
代碼獲然嗤怼:關(guān)注公眾號(hào)瓦糟,回復(fù):20191224 或 圣誕