自从学姐知道我会用Python做九宫格图片后 ,她昨天就问我能帮她P水印吗?说有很多照片要去水印。

这必须啊 ,女生对漂亮的事物是没理由拒绝的,而且还是学姐的要求,动手动手 。

利用Python + OpenCV三步去除水印

去水印需要用到的库:cv2、numpy 。

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

接下来就用我机智的脑壳来推理一下

推理原理:

  1. 标定噪声的特征,使用cv2.inRange二值化标识噪声对图片进行二值化处理 ,具体代码:cv2.inRange(img, np.array([200, 200, 240]), np.array([255, 255, 255])),把[200, 200, 200]~[255, 255, 255]以外的颜色处理为0
  2. 使用OpenCV的dilate方法,扩展特征的区域 ,优化图片处理效果
  3. 使用inpaint方法,把噪声的mask作为参数,推理并修复图片

推理步骤:

  1. 从源图片 ,截取右下角部分,另存为新图片
  2. 识别水印,颜色值为:[200, 200, 200]~[255, 255, 255]
  3. 去掉水印 ,还原图片
  4. 把源图片 、去掉水印的新图片 ,进行重叠合并

参考代码如下:

import cv2
import numpy as np
from PIL import Image
import os
​
dir = os.getcwd()
path = "1.jpg"
newPath = "new.jpg"
img=cv2.imread(path,1)
hight,width,depth=img.shape[0:3]#截取
cropped = img[int(hight*0.8):hight, int(width*0.7):width]  # 裁剪坐标为[y0:y1, x0:x1]
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.save(newPath)

import cv2
import numpy as np
from PIL import Image
import os
​
dir = os.getcwd()
path = "1.jpg"
newPath = "new.jpg"
img=cv2.imread(path,1)
hight,width,depth=img.shape[0:3]#截取
cropped = img[int(hight*0.8):hight, int(width*0.7):width]  # 裁剪坐标为[y0:y1, x0:x1]
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.save(newPath)

成功 ,直接上图
没去水印前:

去了后:

到此这篇关于Python去除图片水印的示例代码文章就介绍到这了,更多Python基础学习资料共享,行业咨询,兼职交流 ,技术交流请点击领取,广告号勿进。

①3000多本Python电子书有
②Python开发环境安装教程有
③Python400集自学视频有
④软件开发常用词汇有
⑤Python学习路线图有
⑥项目源码案例分享有

本文版权归趣营销www.SEOgUrublog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系QQ卍61910465