python opencv随机位置添加水印图
需求:一张水印图A,一张待添加水印的图B,需要将水印A随机添加到B图上,进行线性加深操作,最后resize到指定大小
实现效果(背景图来自网络,侵删):


水印图A,白色背景,黑色字
具体实现代码:
import random
from skimage import io
import numpy as np
from PIL import Image
from torchvision.transforms import transforms
color_aug = transforms.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0)
def Linear_burn(img_1, img_2):
img = img_1 + img_2 - 1
a = np.where(img <= 0, img_2, img)
# a = np.where(a == 0, 1, a)
mask_1 = img < 0
img = img * (1 - mask_1)
# img = (img_2 - img) + img_1 - 1
return img, a
def add_wm(img_1, img_2, new_w=1024, new_h=1024):
img_1 = io.imread(img_1)
if isinstance(img_2, str):
img_2 = io.imread(img_2)
img_2 = np.asarray(Image.fromarray(img_2).resize((1024, 1024)))
img_1 = img_1 / 255.0
img_2 = img_2 / 255.0
# Image.fromarray(np.uint8(img_1 * 255)).show('a')
new_img = np.full((new_w, new_h, 3), 255)
new_img = new_img / 255.0
# Image.fromarray(np.uint8(new_img * 255)).show('a')
i1w, i1h = img_1.shape[1], img_1.shape[0]
rnd_w = random.randint(0, new_w - i1w)
rnd_h = random.randint(0, new_h - i1h)
print(rnd_w, rnd_h)
img_1 = color_aug(Image.fromarray(np.uint8(img_1 * 255)))
new_img[rnd_h:rnd_h + i1h, rnd_w:rnd_w + i1w] = np.asarray(img_1) / 255.0
print(new_img.shape)
# Image.fromarray(np.uint8(new_img * 255)).show('a')
merge_img, a = Linear_burn(new_img, img_2)
Image.fromarray(np.uint8(merge_img * 255)).show('a')
# Image.fromarray(np.uint8(a * 255)).show('a')
return merge_img
if __name__ == '__main__':
img_1 = '/home/siyi/Downloads/watermark (1).png'
img_2 = '/home/siyi/Pictures/01570a5d390482a8012187f478c722.jpg@1280w_1l_2o_100sh.jpg'
merge_img = add_wm(img_1, img_2)
如有错误请指正!