使用Python去除带水印的图片上的黑边

6
我有一堆图片,想通过去除黑色边框使它们统一。通常我使用Imagemagick的Trim功能和模糊参数,但在图像带有水印的情况下,结果不理想。目前,我正在使用opencv和形态变换进行测试,尝试识别水印和图像,然后选择更大的元素,但我对opencv很陌生,遇到了困难。水印可以出现在任何地方,从左下角到右上角。我更喜欢Python代码,但使用类似Imagemagick之类的应用程序也可以。实际上,只使用opencv,我得到了这个结果:
import copy
import cv2

from matplotlib import pyplot as plt


IMG_IN = '/data/black_borders/island.jpg'


# keep a copy of original image
original = cv2.imread(IMG_IN)

# Read the image, convert it into grayscale, and make in binary image for threshold value of 1.
img = cv2.imread(IMG_IN,0)

# use binary threshold, all pixel that are beyond 3 are made white
_, thresh_original = cv2.threshold(img, 3, 255, cv2.THRESH_BINARY)

# Now find contours in it.
thresh = copy.copy(thresh_original)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# get contours with highest height
lst_contours = []
for cnt in contours:
    ctr = cv2.boundingRect(cnt)
    lst_contours.append(ctr)
x,y,w,h = sorted(lst_contours, key=lambda coef: coef[3])[-1]


# draw contours
ctr = copy.copy(original)
cv2.rectangle(ctr, (x,y),(x+w,y+h),(0,255,0),2)


# display results with matplotlib

# original
original = original[:,:,::-1] # flip color for maptolib display
plt.subplot(221), plt.imshow(original)
plt.title('Original Image'), plt.xticks([]),plt.yticks([])

# Threshold
plt.subplot(222), plt.imshow(thresh_original, cmap='gray')
plt.title('threshold binary'), plt.xticks([]),plt.yticks([])

# selected area for future crop
ctr = ctr[:,:,::-1] # flip color for maptolib display
plt.subplot(223), plt.imshow(ctr)
plt.title('Selected area'), plt.xticks([]),plt.yticks([])

plt.show()

结果:

在此输入图片描述


(注:本文为it技术相关内容的翻译,未作解释。)

4
水印摆放在那里可能是有原因的吗? - Hyperboreus
1个回答

10

去除黑色边框:

按照这个链接(我认为是完美的答案)进行操作:
使用OpenCV裁剪黑色边缘

如果想通过指定区域来去除黑色边框,请参考以下链接:
如何使用Python在OpenCV中裁剪图像

如果不想从图像中裁剪任何部分,而是只取ROI(感兴趣区域),那么请参考以下链接:
如何在Python中使用OpenCV复制图像区域

去除水印:

如果水印可能出现在您的图像的任何地方,意味着您无法完全清除水印。您可以对该图像应用模糊效果来使其模糊。它会模糊您的水印。
该链接如下:
https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_filtering/py_filtering.html


如果水印只存在于黑色边框上,那么上述方法将解决您的问题。


谢谢您提供的链接,它们帮助我进一步了解了一些。但是还不足以去除水印。 - kollo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接