请选择 进入手机版 | 继续访问电脑版

深蓝论坛

搜索
查看: 56|回复: 0

python批量去除图片文字水印

[复制链接]

522

主题

4

回帖

2026

积分

管理员

蛮荒网络

Rank: 9Rank: 9Rank: 9

积分
2026

勋章4勋章6冰墩墩滑稽单身狗

发表于 2023-9-1 22:24:23 来自手机 | 显示全部楼层 |阅读模式
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # 需要安装的库
  4. # pip install paddlepaddle -i https://mirrors.aliyun.com/pypi/simple/
  5. # pip install paddleocr -i https://mirrors.aliyun.com/pypi/simple/
  6. # pip install cv2 -i https://mirrors.aliyun.com/pypi/simple/
  7. # pip install numpy -i https://mirrors.aliyun.com/pypi/simple/
  8. # pip install Pillow -i https://mirrors.aliyun.com/pypi/simple/
  9. import os
  10. import cv2
  11. import numpy as np
  12. from PIL import Image
  13. from paddleocr import PaddleOCR, draw_ocr
  14. class DeleteImageWatermark:
  15.     def __init__(self):
  16.         pass
  17.      
  18.     def distinguish_string(self, img_path, lang='ch'):
  19.         """
  20.         得到文字识别结果列表
  21.         img_path: 图片路径
  22.         lang: 默认为识别中文
  23.         return: 返回所有被识别到的文字文本框坐标、文字内容和置信度
  24.         如:[
  25.             [[[1415.0, 977.0], [1482.0, 977.0], [1482.0, 1001.0], [1415.0, 1001.0]], ('小红书', 0.868567168712616)],
  26.             [[[1441.0, 1001.0], [1493.0, 1001.0], [1493.0, 1024.0], [1441.0, 1024.0]], ('小红书', 0.9620211124420166)]
  27.         ]
  28.         """
  29.         orc = PaddleOCR(use_angle_cls=True, lang=lang)
  30.         result = orc.ocr(img_path, cls=True)
  31.         return result
  32.      
  33.     def save_distinguish_result(self, result, img_path, save_path):
  34.         """
  35.         将识别文字的结果输出图片
  36.         """
  37.         image = Image.open(img_path).convert('RGB')
  38.         boxes = [line[0] for line in result]
  39.         txts = [line[1][0] for line in result]
  40.         scores = [line[1][1] for line in result]
  41.         im_show = draw_ocr(image, boxes, txts, scores, font_path='./fonts/simfang.ttf')
  42.         im_show = Image.fromarray(im_show)
  43.         im_show.save(save_path)
  44.      
  45.     def delete_watermark(self, result_list, kw_list, img_path, delete_path):
  46.         """
  47.         将符合目标的水印,模糊化处理
  48.         """
  49.         # 获取所有符合目标的文本框位置
  50.         text_axes_list = []
  51.         for line in result_list:
  52.             for kw in kw_list:
  53.                 if kw in line[1][0]:
  54.                     min_width = int(min(line[0][0][0], line[0][3][0]))
  55.                     max_width = int(max(line[0][1][0], line[0][2][0]))
  56.                     min_hight = int(min(line[0][0][1], line[0][1][1]))
  57.                     max_hight = int(max(line[0][2][1], line[0][3][1]))
  58.                     text_axes_list.append([min_width, min_hight, max_width, max_hight])
  59.                     break
  60.         # 去除水印
  61.         delt = 10  # 文本框范围扩大
  62.         img = cv2.imread(img_path, 1)
  63.         tmp_delete_path = delete_path.split('.')[0] + '_test.' + delete_path.split('.')[1]  # 临时图片地址
  64.         cv2.imwrite(tmp_delete_path, img)
  65.         for text_axes in text_axes_list:
  66.             img = cv2.imread(tmp_delete_path, 1)
  67.             hight, width = img.shape[0:2]
  68.             # 截取图片
  69.             min_width = text_axes[0] - delt if text_axes[0] - delt >= 0 else 0
  70.             min_hight = text_axes[1] - delt if text_axes[1] - delt >= 0 else 0
  71.             max_width = text_axes[2] + delt if text_axes[2] + delt <= width else width
  72.             max_hight = text_axes[3] + delt if text_axes[3] + delt <= hight else hight
  73.             cropped = img[min_hight:max_hight, min_width:max_width]  # 裁剪坐标为[y0:y1, x0:x1]
  74.             cv2.imwrite(delete_path, cropped)  # 保存截取的图片
  75.             imgSY = cv2.imread(delete_path, 1)
  76.             # 图片二值化处理,把[200,200,200]-[250,250,250]以外的颜色变成0
  77.             start_rgb = 200
  78.             thresh = cv2.inRange(imgSY, np.array([start_rgb, start_rgb, start_rgb]), np.array([250, 250, 250]))
  79.             # 创建形状和尺寸的结构元素
  80.             kernel = np.ones((3, 3), np.uint8)  # 设置卷积核3*3全是1;将当前的数组作为图像类型来进&#12175;各种操作,就要转换到uint8类型
  81.             # 扩展待修复区域
  82.             hi_mask = cv2.dilate(thresh, kernel, iterations=10)  # 膨胀操作,白色区域增大,iterations迭代次数
  83.             specular = cv2.inpaint(imgSY, hi_mask, 5, flags=cv2.INPAINT_TELEA)
  84.             # imgSY:输入8位1通道或3通道图像。
  85.             # hi_mask:修复掩码,8位1通道图像。非零像素表示需要修复的区域。
  86.             # specular:输出与imgSY具有相同大小和类型的图像。
  87.             # 5:算法考虑的每个点的圆形邻域的半径。
  88.             # flags:NPAINT_NS基于Navier-Stokes的方法、Alexandru Telea的INPAINT_TELEA方法
  89.             cv2.imwrite(delete_path, specular)
  90.             # 覆盖图片
  91.             imgSY = Image.open(delete_path)
  92.             img = Image.open(tmp_delete_path)
  93.             img.paste(imgSY, (min_width, min_hight, max_width, max_hight))
  94.             img.save(tmp_delete_path)
  95.         os.remove(delete_path)
  96.         os.rename(tmp_delete_path, delete_path)
  97.      
  98.     def has_kw(self, result_list, kw_list):
  99.         """
  100.         图片是否包含目标水印,返回匹配到的文字列表
  101.         """
  102.         result_str_list = []
  103.         for line in result_list:
  104.             for kw in kw_list:
  105.                 if kw in line[1][0]:
  106.                     result_str_list.append(line[1][0])
  107.                     break
  108.         return result_str_list
  109. def main(kw_list, img_path, result_path):
  110.     """
  111.     kw_list: 需要识别的文字列表
  112.     img_path: 输入的图片地址
  113.     result_path: 输出去水印的结果图片地址
  114.     """
  115.     d = DeleteImageWatermark()
  116.     # 识别文字
  117.     result = d.distinguish_string(img_path)
  118.     for line in result:
  119.         print(line)  # 打印识别结果:识别到的文字文本框坐标、文字内容和置信度
  120.      
  121.     # 显示文字识别结果
  122.     d.save_distinguish_result(result, img_path, os.path.dirname(__file__) + '/test_01.jpg')
  123.      
  124.     # 是否含有指定水印
  125.     result_str_list = d.has_kw(result, kw_list)
  126.     if len(result_str_list) > 0:
  127.         # 删除水印
  128.         d.delete_watermark(result, kw_list, img_path, result_path)
  129.         print('共有 %d 处水印,都已删除成功!' % len(result_str_list))
  130.         return True
  131.     else:
  132.         print('无指定水印!')
  133.         return False
  134. if __name__ == '__main__':
  135.     # 图片地址
  136.     #path = os.path.dirname(__file__)
  137.     path=os.getcwd()
  138.     img_path = path + '/去除水印.jpg'
  139.     result_path = path + "/result.jpg"
  140.     # 删除指定水印
  141.     kw_list = [ '快手', '抖音', '网易云']
  142.     main(kw_list, img_path, result_path)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表