本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于騰訊云 作者:Python瘋子

隨著圣誕的到來,想給給自己的頭像加上一頂圣誕帽,如果不是頭像,就加一個圣誕老人陪伴,

image.png
用Python給頭像加上圣誕帽,看了下大概也都是來自2017年大神的文章:https://zhuanlan.zhihu.com/p/32283641
主要流程
素材準備
人臉檢測與人臉關鍵點檢測
調整大小,添加帽子
用dlib的正臉檢測器進行人臉檢測,用dlib提供的模型提取人臉的五個關鍵點
# dlib人臉關鍵點檢測器 predictor_path = "shape_predictor_5_face_landmarks.dat" predictor = dlib.shape_predictor(predictor_path) # dlib正臉檢測器 detector = dlib.get_frontal_face_detector() # 正臉檢測 dets = detector(img, 1) # 如果檢測到人臉 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) # 關鍵點檢測,5個關鍵點 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()

image
調整帽子大小,帶帽
選取兩個眼角的點,求中心作為放置帽子的x方向的參考坐標,y方向的坐標用人臉框上線的y坐標表示,然后我們根據人臉檢測得到的人臉的大小調整帽子的大小,使得帽子大小合適,
# 選取左右眼眼角的點 point1 = shape.part(0) point2 = shape.part(2) # 求兩點中心 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() # 根據人臉大小調整帽子大小 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 # 根據人臉大小調整帽子大小 resized_hat = cv2.resize(rgb_hat,(resized_hat_w,resized_hat_h))
添加小圖示
當然有些同學的頭像不是人物或不能準確的識別無關,所有添加了標識,(即在右下添加小圖示),
小圖示避免單調,是從圖示中隨機選擇一個:
image.png
圖示位置也可以根據愛好調整大小和位置
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)
結果如下
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/235651.html
標籤:Python
