我被我的洪水填充算法困住了:它暂时停止了#34;通常"不该'吨...
在这种情况下:我有一个矩阵512 * 512像素,值为50或100-ish。 50的值正在形成一个正方形,我希望在一个方形中改变值为255(使用填充算法)。
def FF(matrix,x,y,h): #h is chosen <=50
stack=[]
matrix[x,y]=255
stack.append((x,y))
while stack!=[]:
(x,y)=stack[0]
stack.pop()
if matrix[x-1,y] <= h: #Pixel North
matrix[x-1,y]=255
stack.append((x-1,y))
if matrix[x,y+1] <= h: #Pixel East
matrix[x,y+1]=255
stack.append((x,y+1))
if matrix[x+1,y] <= h: #Pixel South
matrix[x+1,y]=255
stack.append((x+1,y))
if matrix[x,y-1] <= h: #Pixel West
matrix[x,y-1]=255
stack.append((x,y-1))
if matrix[x-1,y+1] <= h: #Pixel North East
matrix[x-1,y+1]=255
stack.append((x-1,y+1))
if matrix[x+1,y+1] <= h: #Pixel South East
matrix[x+1,y+1]=255
stack.append((x+1,y+1))
if matrix[x+1,y-1] <= h: #Pixel South West
matrix[x+1,y-1]=255
stack.append((x+1,y-1))
if matrix[x-1,y-1] <= h: #Pixel North West
matrix[x-1,y-1]=255
stack.append((x-1,y-1))
else:
print ('... finished')
return
我不知道为什么,但代码工作了10次但不是更多。
谢谢你,Q。
答案 0 :(得分:1)
问题出在这里:
(x,y)=stack[0] # get the first element of the list
stack.pop() # remove the *last* element
由于您获得了第一个元素,但删除了最后一个元素,因此可能(就像并且可能总是如此), not 将评估所有元素被推送到堆栈上。< / p>
尽管如此,你还是太复杂了。只需写下:
def FF(matrix,x,y,h): #h is chosen <=50
stack=[(x,y)]
m,n = matrix.shape
while stack:
x,y = stack.pop()
if 0 <= x < m and 0 <= y < n and matrix[x,y] <= h: # check bounds and height
matrix[x,y] = 255 # set the value
stack.append((x-1,y-1)) # add all directions to the stack, we check later
stack.append((x,y-1))
stack.append((x+1,y-1))
stack.append((x-1,y))
stack.append((x+1,y))
stack.append((x-1,y+1))
stack.append((x,y+1))
stack.append((x+1,y+1))