python - 递归洪水使用python和numpy填充图像
问题描述
我正在开发一个基于图像特征提取的项目,我正在使用 python 和 numpy,我不想从库中导入任何其他函数。我编写了洪水填充算法的递归实现,该算法的目的是从痣的中心开始并对其进行洪水填充,为简单起见,我正在研究标签矩阵。由于痣内部有一些小孔并且我想将它们移除,我实际上正在为所有像素着色,其中 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/
推荐阅读
- lua - [Logitec][Lua] 我想知道如何强制退出循环
- r - 获取错误“'to' must be afinite number” 为 adstock 绘制函数
- angular - 在 RxJS 管道中多次调用 http.get
- c++ - 将 char* 加入文件系统::path.filename() 或 char[260] 时出现问题
- python - 如何使用 python selenium 在动态页面上单击第一个结果?
- python-3.x - 使用 pandas 清理数据时,是否可以为特定列设置自定义分隔符/分隔符?
- drop-down-menu - 悬停时WordPress导航菜单项相互重叠
- python-3.x - FastAPI:注销后删除cookie不起作用
- apache - 如何在 .htaccess 重定向然后重写
- python - 是否可以设置 tkinter Text 小部件的样式?