给我一个用python自动检测水印并且去除水印的代码
时间: 2024-03-07 12:49:08 浏览: 18
以下是一个使用OpenCV和NumPy库检测和去除图像水印的Python代码:
``` python
import cv2
import numpy as np
# 加载原始图像
img = cv2.imread('watermarked_image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 通过Sobel算子获取图像的梯度
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
gradient = cv2.subtract(sobelx, sobely)
gradient = cv2.convertScaleAbs(gradient)
# 对梯度进行二值化处理
_, thresh = cv2.threshold(gradient, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# 对二值化后的图像进行闭操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# 找到轮廓并筛选出可能的水印区域
_, contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if w/h > 5:
cv2.drawContours(img, [contour], -1, (0, 255, 0), 3)
# 显示结果
cv2.imshow('Result', img)
cv2.waitKey(0)
# 去除水印并保存结果
mask = np.zeros(gray.shape, dtype=np.uint8)
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if w/h > 5:
cv2.drawContours(mask, [contour], -1, 255, -1)
inverted_mask = cv2.bitwise_not(mask)
removed = cv2.inpaint(img, inverted_mask, 3, cv2.INPAINT_TELEA)
cv2.imwrite('removed_watermark.jpg', removed)
```
你只需要将 `watermarked_image.jpg` 替换为你需要处理的图像路径,然后运行代码,就能够自动检测和去除水印了。