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.

35 lines
1.6KB

  1. import cv2
  2. import numpy as np
  3. from PIL import Image, ImageDraw, ImageFont
  4. # PIL添加水印
  5. def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
  6. if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型
  7. img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  8. # 创建一个可以在给定图像上绘图的对象
  9. draw = ImageDraw.Draw(img)
  10. # 字体的格式
  11. fontStyle = ImageFont.truetype(
  12. "../font/simsun.ttc", textSize, encoding="utf-8")
  13. # 绘制文本
  14. draw.text(position, text, textColor, font=fontStyle)
  15. # 转换回OpenCV格式
  16. return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  17. img=cv2.imread("C:\\Users\\chenyukun\\Pictures\\Camera Roll\\a.jpg") # 导入我们需要添加水印的图片
  18. # RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  19. # RGB_img = img
  20. # numpy.zeros(shape,dtype=float,order = 'C')
  21. # np.zeros返回给定形状和类型的新数组,用0填充。
  22. # shape: int 或 int 的元组
  23. # dtype: 类型
  24. # uint8是专门用于存储各种图像的(包括RGB,灰度图像等),范围是从0–255
  25. # blank_img = np.zeros(shape=(RGB_img.shape[0],RGB_img.shape[1],3), dtype=np.uint8)
  26. # font = cv2.FONT_HERSHEY_TRIPLEX
  27. # 添加水印的文字内容
  28. # fontScale字体大小
  29. # cv2.putText(图片img,“文本内容”,(左下角坐标),字体,字体大小,(颜色),线条粗细,线条类型)
  30. frame=cv2AddChineseText(img, "拓恒技术", (123, 123),(0, 255, 0), 30)
  31. cv2.imshow("Watermarked Image", frame)
  32. cv2.imwrite("watermarked.jpg", frame)
  33. cv2.waitKey(100000)
  34. cv2.destroyAllWindows()