Python and add to the picture Santa Claus Christmas hats or small icons

With the arrival of Christmas, I want to give their avatar plus a Christmas hat. If not avatar, add a Santa Claus companionship.

 

Christmas hats in Python to add head, looked at probably come from the 2017 Great God of the article: https://zhuanlan.zhihu.com/p/32283641

The main flow of
material ready to
face detection and face detection key
to resize, add a hat

Face detection using face detector dlib positive, the five key points with dlib provide model extraction face

# 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坐标表示。然后我们根据人脸检测得到的人脸的大小调整帽子的大小,使得帽子大小合适。

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

 

添加小图标

当然有些同学的头像不是人物或不能准确的识别无关,所有添加了标识。(即在右下添加小图标)。

小图标避免单调,是从图标中随机选择一个:

 

代码如下:

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

 

结果如下

 
 

代码获取:关注公众号,回复:20191224 或 圣诞

 

Guess you like

Origin www.cnblogs.com/blogs/p/12092007.html