python怎样在人物图中添加水印

307次阅读
没有评论

python怎样在人物图中添加水印

人物图中添加水印主要流程

素材准备

人脸检测与人脸关键点检测

调整大小,添加帽子

人物图中添加水印步骤

(1)用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()

(2)调整帽子的大小。

选择两个眼角点,找到中心作为放置帽子的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))

(3)添加小图标

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

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

图标位置也可以根据爱好调整大小和位置

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)

以上就是python在人物图中添加水印的方法,希望能对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-04发表,共计2229字。
新手QQ群:570568346,欢迎进群讨论 Python51学习