用Python給頭像加上聖誕帽或聖誕老人小徽章

隨着聖誕的到來,想給給本身的頭像加上一頂聖誕帽。若是不是頭像,就加一個聖誕老人陪伴。dom

用Python給頭像加上聖誕帽,看了下大概也都是來自2017年大神的文章: https://zhuanlan.zhihu.com/p/32283641ui

 

 

 

主要流程spa

素材準備regexp

人臉檢測與人臉關鍵點檢測blog

調整大小,添加帽子圖片

用dlib的正臉檢測器進行人臉檢測,用dlib提供的模型提取人臉的五個關鍵點ip

# 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()

調整帽子大小,帶帽

選取兩個眼角的點,求中心做爲放置帽子的x方向的參考座標,y方向的座標用人臉框上線的y座標表示。而後咱們根據人臉檢測獲得的人臉的大小調整帽子的大小,使得帽子大小合適。ci

# 選取左右眼眼角的點  
              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))

添加小圖標

固然有些同窗的頭像不是人物或不能準確的識別無關,全部添加了標識。(即在右下添加小圖標)。get

小圖標避免單調,是從圖標中隨機選擇一個:string

圖標位置也能夠根據愛好調整大小和位置

代碼以下:

# 水印圖片  
    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)

結果以下

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息