在Python中使用水印删除图像上的黑色边框

时间:2014-02-05 03:32:33

标签: python image opencv border

我有一堆图像,我想通过删除黑色边框来统一。通常我使用Imagemagick的Trim函数和模糊参数,但是如果图像有一些水印,结果就不在这里。

实际上我正在用opencv和形态转换进行一些测试来尝试识别水印和图像,然后选择更大的元素,但我是opencv的新手,我很挣扎。

水印可以在任何地方,从左下角到右上角。

black borders with watermak 1 black borders with watermak 2 black borders with watermak 3

我更喜欢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()

结果:

enter image description here

1 个答案:

答案 0 :(得分:3)

删除黑色边框: -

请点击此链接(我认为完美答案): -
Crop black edges with OpenCV

要通过指定区域删除黑色边框,请点击此链接
How to crop an image in OpenCV using Python

您可以仅使用ROI(感兴趣区域),而不是从图像中裁剪任何部分。为此,请点击此链接,
How to copy a image region using opencv in python?

删除水印: -

如果水印可能出现在图像中的任何位置,则无法完全清除水印。只是你可以对该图像应用模糊效果。它会模糊你的水印。
其链接:
https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_filtering/py_filtering.html

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