python去除图片水印(适用于背景单一, 类似于PS中印章工具)

python去除图片水印(适用于背景单一, 类似于PS中印章工具)

Fre_soe 210 2022-11-07
"""
@File    :   auto_convert_file.py
@Time    :   2022/08/24 17:13:16
@Author  :   JuYongkang
@Version :   1.0
@Contact :   j_juyongkang@163.com
@Desc    :   图片处理脚本(去除左上角水印)
"""

import cv2
import numpy as np
from PIL import Image
import os


def deal_pic(path, newpath, lis):
    dir = os.getcwd()

    img = cv2.imread(path, 1)
    hight, width, depth = img.shape[0:3]

    # 截取
    cropped = img[lis[0]:int(hight*lis[1]), lis[2]:int(width*lis[3])]  # 裁剪坐标为[y0:y1, x0:x1]
    cv2.imwrite(dir+'/area.jpg', cropped)
    cv2.imwrite(newpath, cropped)
    imgSY = cv2.imread(newpath, 1)

    # 图片二值化处理,把[200,200,200]-[250,250,250]以外的颜色变成0
    thresh = cv2.inRange(imgSY, np.array([200, 200, 200]), np.array([250, 250, 250]))
    # 创建形状和尺寸的结构元素
    kernel = np.ones((3, 3), np.uint8)
    # 扩展待修复区域
    hi_mask = cv2.dilate(thresh, kernel, iterations=10)
    specular = cv2.inpaint(imgSY, hi_mask, 5, flags=cv2.INPAINT_TELEA)
    cv2.imwrite(newpath, specular)

    # 覆盖图片
    imgSY = Image.open(newpath)
    img = Image.open(path)
    # img.paste(imgSY, (int(width * 0.7), int(hight * 0.8), width, hight))
    img.paste(imgSY, (0, 0, int(width * 0.25), int(hight * 0.03)))
    img.save(newpath)
    print('{}图片修复完成~'.format(path))




if __name__ == '__main__':
    # 源图片文件夹
    source_path = 'C:/Users/JK/Documents/Projects/Test/img/'
    # 目标文件夹
    target_path = 'C:/Users/JK/Documents/Projects/Test/img_new/'
    # 裁剪坐标比例(即图中文字所占区域比例, 整图为1, 如图片尺寸, 文字位置相同, 则使用这个已经调好的比例就可以)
    # 裁剪坐标为[y0:y1, x0:x1] y0, y1, x0, x1均为裁剪区域占比
    lis = [0, 0.03, 0, 0.25]

    for path in os.listdir(source_path):
        picpath = os.path.join(source_path, path)
        savepath = os.path.join(target_path, path)
        deal_pic(picpath, savepath, lis)
    print('文件夹下文件全部转化完成')