You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.7KB

  1. import cv2
  2. import numpy as np
  3. def watermark(src_path, mask_path, alpha=1):
  4. # 读取原图
  5. img = src_path
  6. # 获取原图高和宽度
  7. h, w = img.shape[0], img.shape[1]
  8. # 读取LOG
  9. mask = mask_path
  10. if w > h:
  11. rate = int(w * 0.1) / mask.shape[1]
  12. else:
  13. rate = int(h * 0.1) / mask.shape[0]
  14. mask = cv2.resize(mask, None, fx=rate, fy=rate, interpolation=cv2.INTER_NEAREST)
  15. mask_h, mask_w = mask.shape[0], mask.shape[1]
  16. mask_channels = cv2.split(mask)
  17. dst_channels = cv2.split(img)
  18. b, g, r, a = cv2.split(mask)
  19. # 计算mask在图片的坐标
  20. ul_points = (int(h * 0.9), int(int(w / 2) - mask_w / 2))
  21. dr_points = (int(h * 0.9) + mask_h, int(int(w / 2) + mask_w / 2))
  22. for i in range(3):
  23. dst_channels[i][ul_points[0]: dr_points[0], ul_points[1]: dr_points[1]] = dst_channels[i][
  24. ul_points[0]: dr_points[0],
  25. ul_points[1]: dr_points[1]] * (
  26. 255.0 - a * alpha) / 255
  27. dst_channels[i][ul_points[0]: dr_points[0], ul_points[1]: dr_points[1]] += np.array(
  28. mask_channels[i] * (a * alpha / 255), dtype=np.uint8)
  29. dst_img = cv2.merge(dst_channels)
  30. # cv2.imwrite(r'd:\1_1.jpg', dst_img)
  31. return dst_img
  32. import time
  33. # 导入我们将要使用的logo
  34. logo = "logo.png"
  35. img2 = "a.jpg"
  36. time11 = time.time()
  37. a = watermark(img2, logo)
  38. time12 = time.time()
  39. print(time12-time11)
  40. cv2.imshow("Watermarked Image", a)
  41. cv2.imwrite("watermarked.jpg", a)
  42. cv2.waitKey(100000)