使用python和numpy递归洪水填充图像

2024-06-16 10:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个基于图像特征提取的项目,我使用python和numpy,我不想从库中导入任何其他函数。 我写了一个递归实现的泛洪填充算法,这个算法的目的是从一个鼹鼠的中心开始泛洪填充它,为了简单起见我正在研究标签的矩阵。因为痣里面有一些小孔,我想把它们去掉,我实际上是用痣的颜色给所有的像素着色,这也是平滑边缘,这对我来说是件好事。 这是我的职责

    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语言,但我知道递归和终止条件对我来说似乎足够了。 提前谢谢!你知道吗


Tags: orself算法labelsreturnifcountfill
1条回答
网友
1楼 · 发布于 2024-06-16 10:29:31

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

相关问题 更多 >