处理图片水印:
下面的函数可以处理局部的水印,详细请看函数文档
该函数适合处理位置固定的水印.
def process_water_paper(original_name=None, box=None):
"""
:param original_name: 字符串形式接受, 需要处理的文件名称
:param box: 元组形式接收, (水印的宽度, 水印的高度, 水印右边界距离图片右边界距离, 水印下边界距离图片下边界距离)
:return: True(处理成功), False(处理失败)
"""
# 水印下边界距离图片下边界的距离(像素值)
border_height = box[3]
# 水印右边界距离图片右边界的距离(像素值)
border_width = box[2]
# # 水印宽高
# 设置高
waterpaper_width = box[0]
# 设置宽
waterpaper_height = box[1]
try:
# # 设置水印的区域(使用像素值,请自行量图)
path = original_name
img = cv2.imread(path)
height, width, depth = img.shape[0:3]
# 选择水印区域 (需要处理的)
roi = img[(height - (waterpaper_height + border_height)):height-border_height, (width - (waterpaper_width + border_width)):width-border_width]
# # 图片二值化处理,把[240, 240, 240]~[255, 255, 255]以外的颜色变成0
# 根据原图上水印的像素值,顺序B-G-R 这是要修改的范围
thresh = cv2.inRange(roi, np.array([120, 120, 120]), np.array([255, 255, 255]))
# 创建形状和尺寸的结构元素
kernel = np.ones((3, 3), np.uint8)
# 扩张待修复区域
hi_mask = cv2.dilate(thresh, kernel, iterations=1)
specular = cv2.inpaint(roi, hi_mask, 5, flags=cv2.INPAINT_TELEA)
# 将修改区域的像素值替换为修改后的 (仅修改局部)
img[(height-(waterpaper_height + border_height)):height-border_height, (width-(waterpaper_width + border_width)):width-border_width] = specular
cv2.imwrite(path, img)
return True
except Exception as e:
print(e)
return False
在水印位置覆盖新的水印
def process_images_combine(original=None, waterpaper=None, box=None):
"""
:param original: 处理的图片的路径
:param waterpaper: 水印的路径
:param box: 元组形式接收, (水印的宽度, 水印的高度, 水印右边界距离图片右边界距离, 水印下边界距离图片下边界距离)
:return: None
"""
# 读取水印处理后的图片
imp = Image.open(original)
height = imp.size[1]
width = imp.size[0]
# 读取需要添加的水印
imq = Image.open(waterpaper)
waterpaper_height = imq.size[1]
waterpaper_width = imq.size[0]
# 计算处理水印位置处的坐标
process_height = height - waterpaper_height - box[2]
process_width = width - waterpaper_width - box[3]
# process_height = height - waterpaper_height
# process_width = width - waterpaper_width
# 按照计算的坐标合并图片 (解决 png 类透明图片,不透明的问题)
r, g, b, a = imq.split()
imp.paste(imq, (process_width, process_height), mask=a)
# 覆盖原图
imp.save(original)
参考链接: