我正在基于从图像中提取特征的项目中,我正在将nunmpy与python配合使用,并且无法从库中导入其他任何功能。我写了一个泛洪填充算法的递归实现,该算法的目的是从痣的中心开始并进行泛洪填充,为简单起见,我正在研究标签矩阵。由于痣内部有一些小孔,我想去除它们,所以我实际上是用痣的颜色给所有像素中的8个相邻像素中的4个进行着色,这也使边缘平滑,这对我的目的是一件好事。这是我的功能
def flood_fill(self, posi, posj, targetcolor, color):
"""
recursive function to flood fill the mole starting from its centroids.
"""
if(posi==-1 or posj == -1 or posi == self.N1 or posj == self.N2):
return
if(self.labels[posi][posj] == color):
return
if(self.labels[posi][posj] != targetcolor):
c=0
if(self.labels[posi+1][posj] == targetcolor or self.labels[posi+1][posj] == color):
c+=1
if(self.labels[posi][posj+1] == targetcolor or self.labels[posi][posj+1] == color):
c+=1
if(self.labels[posi-1][posj] == targetcolor or self.labels[posi-1][posj] == color):
c+=1
if(self.labels[posi][posj-1] == targetcolor or self.labels[posi][posj-1] == color):
c+=1
if(self.labels[posi+1][posj+1] == targetcolor or self.labels[posi+1][posj+1] == color):
c+=1
if(self.labels[posi+1][posj-1] == targetcolor or self.labels[posi+1][posj+1] == color):
c+=1
if(self.labels[posi-1][posj-1] == targetcolor or self.labels[posi-1][posj-1] == color):
c+=1
if(self.labels[posi-1][posj+1] == targetcolor or self.labels[posi-1][posj+1] == color):
c+=1
if(c >= 4):
self.labels[posi][posj] = color
return
self.labels[posi][posj] == color
if(posi>self.maxi):
self.maxi = posi
if(posj>self.maxj):
self.maxj = posj
if(posi<self.mini):
self.mini = posi
if(posj<self.minj):
self.minj = posj
self.flood_fill(posi-1, posj, targetcolor, color, count+1)
self.flood_fill(posi+1, posj, targetcolor, color, count+1)
self.flood_fill(posi, posj-1, targetcolor, color, count+1)
self.flood_fill(posi, posj+1, targetcolor, color, count+1)
self.flood_fill(posi+1, posj+1, targetcolor, color, count+1)
self.flood_fill(posi-1, posj+1, targetcolor, color, count+1)
self.flood_fill(posi+1, posj-1, targetcolor, color, count+1)
self.flood_fill(posi-1, posj-1, targetcolor, color, count+1)
return
我不明白我的代码有什么问题,为什么它不起作用,spyder停止执行而没有任何消息,我尝试增加递归限制,但是我认为问题不在于此。我是python语言的新手,但我知道递归,并且终止条件对我来说似乎足够。预先感谢!
self.flood_fill(posi-1, posj, targetcolor, color, count+1)
,这里您传递了一个额外的参数count+1
,但您声明的函数定义仅具有前4个参数。这看起来不像递归。看一下这个。 https://www.geeksforgeeks.org/flood-fill-algorithm-implement-fill-paint/