OpenCV 图片去水印(不需要自己做水印模板)

您所在的位置:网站首页 怎样把微博图片去水印 OpenCV 图片去水印(不需要自己做水印模板)

OpenCV 图片去水印(不需要自己做水印模板)

2024-07-10 16:55| 来源: 网络整理| 查看: 265

图片去水印的思路

准备一张有水印的图片用绘画工具在有水印的图片上框出水印位置利用findContours函数查找水印所在的位置初始化一个与原图像大小相同的0矩阵将获取到的水印图片定位到初始化的矩阵中利用inpaint函数进行水印的去除

详细步骤 准备一张带有水印的图片,命名为watermark.png 在这里插入图片描述 将水印部分用绘图工具框出来,并名为reference.png 在这里插入图片描述 读取模板图片转换为灰度图,并记录图片的大小

# 读取模板图像 image = cv2.imread("reference.png") image_gary = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) # 转换成灰度图 print(image.shape) # (255, 386, 3)

初始化一个与原图像大小相同的矩阵

temp = np.zeros((255,386)) temp = temp.astype(np.uint8)

在这里插入图片描述 查找模板中标记水印的位置,记录水印的位置和大小

ret,thresh = cv2.threshold(image_gary, 250, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(thresh, 2, 1) cnt=contours[0] x, y, w, h = cv2.boundingRect(cnt) img = cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("contour2.jpg", img) cv2.waitKey(0)

在这里插入图片描述 显示水印图片

image2 = cv2.imread("watermark.png") roi = image2[y:y+h,x:x+w,0:3] cv2.imshow("roi",roi) cv2.waitKey(0)

在这里插入图片描述 对水印图片进行二值化和卷积处理

roi = cv2.cvtColor(roi, cv2.COLOR_BGRA2GRAY) ret,roi = cv2.threshold(roi, 60, 100, cv2.THRESH_BINARY) # 参数可调节,因图片的像素而异 roi = cv2.morphologyEx(roi,cv2.MORPH_ELLIPSE,(5,5)) # 参数可调节,因图片的像素而异 cv2.imshow("roi",roi) cv2.waitKey(0)

在这里插入图片描述 将水印图片定位到初始矩阵中

roi2 = temp[y:y+h,x:x+w] roi3 = cv2.add(roi, roi2) temp[y:y+h,x:x+w] = roi3 cv2.imshow("temp",temp) cv2.waitKey(0)

在这里插入图片描述 利用inpaint函数去除图片的水印

dst = cv2.inpaint(image2, temp, 3, cv2.INPAINT_NS) # 使用INPAINT_TELEA算法进行修复 cv2.imshow('TELEA', dst) cv2.waitKey(0)

在这里插入图片描述 注意:这里的水印虽然去除,但是还有些明显的地方,只要对水印图片roi进行处理的精度越高(调参),图像水印就越不明显。

整体代码

# -*- coding: utf-8 -*- import cv2 import numpy as np # 读取模板图像 image = cv2.imread("reference.png") image_gary = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) # 转换成灰度图 print(image.shape) # 初始化一个与原图像等同的矩阵 temp = np.zeros((255,386)) temp = temp.astype(np.uint8) # 查找图像中的矩阵 ret,thresh = cv2.threshold(image_gary, 250, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(thresh, 2, 1) cnt=contours[0] x, y, w, h = cv2.boundingRect(cnt) img = cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # 显示水印图片 image2 = cv2.imread("watermark.png") roi = image2[y:y+h,x:x+w,0:3] roi = cv2.cvtColor(roi, cv2.COLOR_BGRA2GRAY) ret,roi = cv2.threshold(roi, 80, 100, cv2.THRESH_BINARY) roi = cv2.morphologyEx(roi,cv2.MORPH_ELLIPSE,(5,5)) # 将水印图片赋值给初始化的矩阵图片 roi2 = temp[y:y+h,x:x+w] roi3 = cv2.add(roi, roi2) temp[y:y+h,x:x+w] = roi3 dst = cv2.inpaint(image2, temp, 30, cv2.INPAINT_NS) # 使用INPAINT_TELEA算法进行修复 cv2.imshow('TELEA', dst) cv2.waitKey(0)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3