当前位置:   article > 正文

Python编程-使用OpenCV和Numpy库实现图片去水印(附代码)_opencv去除水印

opencv去除水印

目录

安装OpenCV和NumPy库

开始

读取图像

选取水印位置

删除指定位置的水印

去除并修复水印(完整代码)

优化修复方法

效果(标红区域是原水印位置)

注意


安装OpenCV和NumPy库

  1. cv2是基于OpenCV的图像处理库,可以对图像进行腐蚀,膨胀等操作;
  2. Numpy这是一个强大的处理矩阵和维度运算的库。
  1. pip install opencv-python
  2. pip install numpy

开始

读取图像

cv2的三个基本函数:使用cv2.imread()cv2.imshow()cv2.imwrite()分别可以读取、显示和保存图像。

  1. import cv2
  2. import numpy as np
  3. def remove_watermark(image_path, output_path):
  4. # 读取图像, image_path='test.png'
  5. image = cv2.imread(image_path)
  6. cv2.imshow('test.png', image)
  7. cv2.waitKey(0)
  8. cv2.imwrite('test_2.png', image)

选取水印位置

为了能够图片上点击水印的位置,并获取该水印的定位和大小,我们需要一个图形用户界面(GUI)库来与用户进行交互。Python中常用的GUI库有tkinterPyQtwxPython等。下面将使用tkinter库来演示如何实现这个功能。

  1. import tkinter as tk
  2. from tkinter import messagebox
  3. from PIL import Image, ImageTk
  4. pos = []
  5. def get_click_positions(canvas, image, root):
  6. """获取用户点击的四个角位置"""
  7. positions = []
  8. click_count = 0
  9. def on_click(event):
  10. print("点击")
  11. nonlocal click_count, positions
  12. x = event.x
  13. y = event.y
  14. positions.append((x, y))
  15. click_count += 1
  16. if click_count == 4:
  17. # 用户已点击四个角,关闭画布并返回位置
  18. canvas.unbind('<Button-1>')
  19. print(f"Watermark positions: {positions}")
  20. # 计算水印大小和位置
  21. # positions.sort(key=lambda p: p[0] + p[1]) # 根据点击顺序排序
  22. top_left, top_right, bottom_right, bottom_left = positions
  23. x1, y1 = top_left
  24. x2, y2 = bottom_right
  25. width = x2 - x1
  26. height = y2 - y1
  27. print(f"Watermark position: ({x1}, {y1}), Size: ({width}x{height})")
  28. # 关闭程序
  29. root.destroy()
  30. # canvas.bind('<Button-1>', on_click)
  31. canvas.config(cursor="cross") # 设置鼠标样式为十字线
  32. # 显示图片
  33. photo = ImageTk.PhotoImage(image)
  34. image_label = tk.Label(canvas, image=photo)
  35. image_label.image = photo
  36. image_label.place(x=0, y=0, relwidth=1, relheight=1)
  37. image_label.bind('<Button-1>', on_click)
  38. # canvas.pack(fill=tk.BOTH, expand=tk.YES)
  39. canvas.pack()
  40. messagebox.showinfo("Instructi
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/975417
推荐阅读
相关标签
  

闽ICP备14008679号