如何在此类图像中找到最大的空白空间?
我想在类似于我在下面发布的图像中找到空白区域(黑色区域),其中散布着大小随机的块。
通过空白空间,我指的是这种可能的开放领域(我对该区域没有特别的下限,但我想提取图像中出现的前 3-4 个最大的区域。)对几何形状也没有限制他们可以拿走,但这些空位不能包含任何蓝色方块。
解决这个问题的最佳方法是什么?
到目前为止我所做的:
我的原始图像实际上是这样的。我确定了所有的点,根据一定的距离阈值对它们进行分组,并在它们周围应用凸包。我不确定如何进一步进行。任何帮助将不胜感激。谢谢!
回答
这是 Python/OpenCV 中使用距离变换找到 X 之间最大欧几里得距离的一种方法。
输入:
import cv2
import numpy as np
import skimage.exposure
# read image
img = cv2.imread('xxx.png')
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold to binary and invert so background is white and xxx are black
thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)[1]
thresh = 255 - thresh
# add black border around threshold image to avoid corner being largest distance
thresh2 = cv2.copyMakeBorder(thresh, 1,1,1,1, cv2.BORDER_CONSTANT, (0))
h, w = thresh2.shape
# create zeros mask 2 pixels larger in each dimension
mask = np.zeros([h + 2, w + 2], np.uint8)
# apply distance transform
distimg = thresh2.copy()
distimg = cv2.distanceTransform(distimg, cv2.DIST_L2, 5)
# remove excess border
distimg = distimg[1:h-1, 1:w-1]
# get max value and location in distance image
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(distimg)
# scale distance image for viewing
distimg = skimage.exposure.rescale_intensity(distimg, in_range='image', out_range=(0,255))
distimg = distimg.astype(np.uint8)
# draw circle on input
result = img.copy()
centx = max_loc[0]
centy = max_loc[1]
radius = int(max_val)
cv2.circle(result, (centx, centy), radius, (0,0,255), 1)
print('center x,y:', max_loc,'center radius:', max_val)
# save image
cv2.imwrite('xxx_distance.png',distimg)
cv2.imwrite('xxx_radius.png',result)
# show the images
cv2.imshow("thresh", thresh)
cv2.imshow("thresh2", thresh2)
cv2.imshow("distance", distimg)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
距离变换图像:
到 Xs 的最大距离区域:
文字信息:
中心 x,y: (179, 352) 半径:92.5286865234375