python + cv2实现图片加水印

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36810544/article/details/89671249

网上好多都是直接用写txt的方式实现的,其实实际中美工会提供水印图片,让添加进去。用cv2读取水印图片的时候,后面的参数设置为-1即可读出透明度通道,然后在原图的指定位置将水印图片和原图像的像素进行融合即可。

import cv2
import numpy as np

def watermark(src_path, mask_path, alpha = 0.3):
    img = cv2.imread(src_path)
    h,w = img.shape[0], img.shape[1]
    mask = cv2.imread(mask_path, -1)
    if w > h:
        rate = int(w * 0.1) / mask.shape[1]
    else:
        rate = int(h * 0.1) / mask.shape[0]
    mask = cv2.resize(mask, None, fx=rate, fy=rate)
    mask_h, mask_w = mask.shape[0], mask.shape[1]
    mask_channels = cv2.split(mask)
    dst_channels = cv2.split(img)
    b, g, r, a = cv2.split(mask)

    # 计算mask在图片的坐标
    ul_points = (int(h * 0.9), int(int(w/2) - mask_w / 2))
    dr_points = (int(h * 0.9) + mask_h, int(int(w/2) + mask_w / 2))
    for i in range(3):
        dst_channels[i][ul_points[0] : dr_points[0], ul_points[1] : dr_points[1]] = dst_channels[i][ul_points[0] : dr_points[0], ul_points[1] : dr_points[1]] * (255.0 - a * alpha) / 255
        dst_channels[i][ul_points[0]: dr_points[0], ul_points[1]: dr_points[1]] += np.array(mask_channels[i] * (a * alpha / 255), dtype=np.uint8)
    dst_img = cv2.merge(dst_channels)
    # cv2.imwrite(r'd:\1_1.jpg', dst_img)
    return dst_img

原图
在这里插入图片描述水印图:
在这里插入图片描述
合成之后的图,分别选择alpha=1 和 alpha=0.3
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_36810544/article/details/89671249