使用 python 提取二值图像中的连接像素

Extract connected pixels in a binary image using python

我有一个二值图像 - 黑色像素 (0) 和白色 (1)。 我想编写一个函数来获取图像和黑色像素的位置 - x 和 y 以及 returns 与给定像素连接(连接 = 8-连接)的所有像素的位置,以及所有连接像素的总数。
例如,如果这是我的图片:

1 1 1 1
1 0 0 1
1 1 0 1
1 1 1 1

我给函数像素 (1,1) 输出将是:

count=3
x=[1,2,2]
y=[1,1,2]

这是我所做的:

def find_connectivity(img,i,j,count,x,y):
    sys.setrecursionlimit(50000)
    if(img[i][j]==0):
        img[i][j]=2

        count=count+1
        xx=x
        yy=y
        xx=xx.append(i)
        yy=yy.append(j)
    rows=[-1, 0 ,1]
    cols=[-1, 0 ,1]
    for r in rows:
        for c in cols:
            if(img[i+r][j+c]==0):
                count,x,y= find_connectivity(img,i+r,j+c,count,x,y)
    return count,x,y

当我初始计数为0,x和y为[]。 例如,在前面的示例中,对函数的调用将是:

[count,x,y]=find_connectivity(img,1,1,0,[],[])

现在,此功能适用于相当大的群体 (5300+) - 但如果超过这个数量,我会收到一条消息 "python.exe has stop working"。 错误详情如下:

Application Timestamp:  5665e7c3
Fault Module Name:  ntdll.dll
Fault Module Version:   6.1.7601.19045
Fault Module Timestamp: 56259295
Exception Code: c00000fd
Exception Offset:   00000000000510a1
OS Version: 6.1.7601.2.1.0.256.48
Locale ID:  1033
Additional Information 1:   2a7e
Additional Information 2:   2a7edff1635197ae43266443b8d73ae8
Additional Information 3:   6edf
Additional Information 4:   6edf0945fe78222ec4c56cecff238926 

我想这是因为递归 - 但我想不出另一种有效的方法。

openCV/numpy/other 中是否有可以帮助我的功能? 或者有没有办法通过递归来防止崩溃?

谢谢!

如果您对轮廓不感兴趣,可以简单地使用种子洪水填充算法。另见区域增长、区域填充

使用您的点作为种子点并用 0 或 1 以外的某个值填充该区域。计算具有该新值的像素或列出它们以获得数字及其坐标。

http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html 请参阅 floodFill。

您应该像下面这样使用 Breadth-first search

import queue
def find_connectivity(img, i, j):
    dx = [0, 0, 1, 1, 1, -1, -1, -1]
    dy = [1, -1, 0, 1, -1, 0, 1, -1]
    x = []
    y = []
    q = queue.Queue()
    if img[i][j] == 0:
        q.put((i, j))
    while q.empty() == False:
        u, v = q.get()
        x.append(u)
        y.append(v)
        for k in range(8):
            xx = u + dx[k]
            yy = v + dy[k]
            if img[xx][yy] == 0:
                img[xx][yy] = 2
                q.put((xx, yy))
    return x, y