import cv2
import os
import numpy as np
from PIL import Image,ImageFont,ImageDraw
#给图片加水印
def create_watermark(img_path, save_to, text, position):
# img = cv2.imread(img_path)
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
sp = img.shape
h = sp[0]
w = sp[1]
c = sp[2]
# 给图片添加文字水印
# img2 = cv2.putText(img, text, (100, 100), cv2.LINE_AA, 2, (249, 249, 249), 4) #这里不支持中文水印
# # 保存图片
# cv2.imwrite(save_to, img2)
# # 下面是将生成的图片再弹窗中显示
# cv2.imshow('img', img2)
# cv2.waitKey(0)
# cv2.destoryAllWindows('img')
#基于PIL实现中文水印添加
pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) #BGR 2 RGB
font = ImageFont.truetype(font="simfang.ttf", size=20) #windows的字体,linux下换字体
color = (255, 255, 255)
pos = (int(w * 0.5) - 50, int(h * 0.5))
if position == "right_bottom":
pos = (w-150, h-30)
draw = ImageDraw.Draw(pil_img)
draw.text(pos, text, font=font, fill=color)
cv_img = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR)
cv2.imshow('img', cv_img)
if os.path.exists(save_to) == False:
os.mkdir(save_to)
# cv2.imwrite(save_to + , cv_img) #不支持中文路径
cv2.imencode(".jpg", cv_img)[1].tofile(save_to + img_path.split("\\")[-1])
if __name__ == "__main__":
# create_watermark("P:\\0.jpg", "P:\\split\\watermark.jpg", "@古代书法欣赏", "right_bottom")
#批量处理
dir = 'P:\\split\\tif_split\\001_0\\'
list = os.listdir(dir) # 列出文件夹下所有的目录与文件
for i in range(0, len(list)):
path = os.path.join(dir, list[i])
print("处理文件:%s" % path)
if os.path.isfile(path):
try:
create_watermark(path, "P:\\split\\watermark\\001_0\\", "@古代书法欣赏", "right_bottom")
except IOError:
print("IOError")