我致力于在 python 中实现区域增长算法。但是当我在输出上运行这段代码时,我得到了没有错误的黑色图像。在输入图像上使用 CV 阈值函数,对于种子值,我使用鼠标单击将 x、y 值存储在元组中。
def get8n(x, y, shape):
out = []
if y-1 > 0 and x-1 > 0:
out.append( (y-1, x-1) )
if y-1 > 0 :
out.append( (y-1, x))
if y-1 > 0 and x+1 < shape[1]:
out.append( (y-1, x+1))
if x-1 > 0:
out.append( (y, x-1))
if x+1 < shape[1]:
out.append( (y, x+1))
if y+1 < shape[0] and x-1 > 0:
out.append( ( y+1, x-1))
if y+1 < shape[0] :
out.append( (y+1, x))
if y+1 < shape[0] and x+1 < shape[1]:
out.append( (y+1, x+1))
return out
def region_growing(img, seed):
list = []
outimg = np.zeros_like(img)
list.append((seed[0], seed[1]))
while(len(list)):
pix = list[0]
outimg[pix[0], pix[1]] = 255
for coord in get8n(pix[0], pix[1], img.shape):
if img[coord[0], coord[1]] > 0:
outimg[coord[0], coord[1]] = 255
list.append((coord[0], coord[1]))
list.pop(0)
return outimg
def on_mouse(event, x, y, flags, params):
if event == cv2.EVENT_LBUTTONDOWN:
print 'Seed: ' + str(x) + ', ' + str(y)
clicks.append((y,x))
clicks = []
image = cv2.imread('lena.jpg', 0)
ret, img = cv2.threshold(image, 200, 255, cv2.THRESH_BINARY)
cv2.namedWindow('Input')
cv2.setMouseCallback('Input', on_mouse, 0, )
cv2.imshow('Input', img)
cv2.waitKey()
seed = clicks[-1]
cv2.imshow('Region Growing', region_growing(img, seed))
cv2.waitKey()
cv2.destroyAllWindows()
原文由 David 发布,翻译遵循 CC BY-SA 4.0 许可协议
我在使用您的 get8n() 函数时遇到了一些问题,所以我重写了它。我相信下面的代码可以满足您的要求。 region_growing() 函数中有两行被注释掉了。如果您取消注释它们,它们将显示处理过程中发生的事情的动画。这是一种可视化代码并让您了解哪里出了问题的好方法。
此外,在您的代码中,您可以将已经处理过的像素添加到“待处理”列表中。这导致了无限循环。我添加了一项检查,以防止将已经处理过的像素添加回列表中。
这是点击她帽子左侧的结果: