我有一个带有神经网络的项目,该项目可处理如下图像:
如您所见,它在页边空白处有一个空格。我的问题是,该空间是否会干扰网络结果,如果是,考虑到空白区域在所有图像中的大小和位置都不相同,如何使用python / openCV仅剪切空白区域
另一个例子:
(打开图像以清楚地看到空白)
最佳答案
这是在Python / OpenCV中用黑色填充空间的一种方法。
用1像素宽的白色边框填充整个图像。然后从左上角(0,0)用黑色填充填充的图像。然后删除1像素宽的边框。假定您在原始图像的侧面没有真实数据的纯白色像素。
输入1:
import cv2
import numpy as np
# read image
img = cv2.imread('border_image1.jpeg')
#img = cv2.imread('border_image2.jpeg')
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# add 1 pixel white border all around
pad = cv2.copyMakeBorder(gray, 1,1,1,1, cv2.BORDER_CONSTANT, value=255)
h, w = pad.shape
# create zeros mask 2 pixels larger in each dimension
mask = np.zeros([h + 2, w + 2], np.uint8)
# floodfill outer white border with black
img_floodfill = cv2.floodFill(pad, mask, (0,0), 0, (5), (0), flags=8)[1]
# remove border
img_floodfill = img_floodfill[1:h-1, 1:w-1]
# save cropped image
cv2.imwrite('border_image1_floodfilled.png',img_floodfill)
#cv2.imwrite('border_image2_floodfilled.png',img_floodfill)
# show the images
#cv2.imshow("thresh", thresh)
cv2.imshow("pad", pad)
cv2.imshow("img_floodfill", img_floodfill)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果1:
沿对角线边缘保留的白色区域可能是因为发布的图像是PNG图像的JPG版本。 JPG的压缩有损,会导致这种影响。请注意,我使用了5个灰度级的较低差异,以使该区域的发白值与纯白色有些偏离。这减少了多余的白色,但没有将其完全去除。但是,它可能已经改变了图像侧面的一些白色数据像素。因此,您可以将其恢复为0,但在该对角线区域将剩余更多白色。
输入2:
结果2:
关于python - 如何在图像上方剪切空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62434997/