首页 > 解决方案 > 递归洪水使用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 语言的新手,但我知道递归和终止条件对我来说似乎足够了。提前致谢!

标签: pythonpython-3.ximagenumpyflood-fill

解决方案


self.flood_fill(posi-1, posj, targetcolor, color, count+1)在这里,您传递了一个额外的参数count+1,但您声明的函数定义只有前 4 个参数。这看起来不像递归。看一下这个。https://www.geeksforgeeks.org/flood-fill-algorithm-implement-fill-paint/


推荐阅读