【发布时间】:2014-03-01 08:17:56
【问题描述】:
我有一堆图像,我想通过去除黑色边框来统一化。通常我使用带有模糊参数的 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()
结果:
【问题讨论】:
-
会不会是水印有什么原因?
标签: python image opencv border