代码如下
import cv2
import numpy
from PIL import Image, ImageFont, ImageDraw
def watermark(image, text, size=None, color=None, alpha=1.0, position=0):
back = Image.fromarray(image).convert('RGBA') if type(image) is numpy.ndarray else image.convert('RGBA')
fore = Image.new(back.mode, back.size, (0, 0, 0, 0))
size = min(back.width, back.height) // 20 if size is None else max(20, size)
font = ImageFont.truetype("arial.ttf", size)
w, h = font.getsize(text)
rgba = (255, 255, 255) if color is None else color
rgba = rgba + (int(255 * alpha),)
if position == 0:
x, y = (back.width - w) // 2, (back.height - h) // 2
elif position == 1:
x, y = 8, 4
elif position == 2:
x, y = back.width - w - 8, 4
elif position == 3:
x, y = back.width - w - 8, back.height - h - 8
elif position == 4:
x, y = 8, back.height - h - 8
draw = ImageDraw.Draw(fore)
draw.text((x, y), text, rgba, font)
output = Image.alpha_composite(back, fore).convert('RGB')
return numpy.uint8(output) if type(image) is numpy.ndarray else output
img_src = '1.png'
image = cv2.imread(img_src, cv2.IMREAD_COLOR)
image = watermark(image, 'watermark', alpha=0.3, position=3, size=80)
cv2.imwrite('test.png', image)
结果如下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b91538be160a88d73f26bd7e44247954.png#pic_center)