Python 连接断开的组件,只要不需要超过n个像素即可

Python 连接断开的组件,只要不需要超过n个像素即可,python,opencv,scipy,scikit-image,Python,Opencv,Scipy,Scikit Image,我想知道是否有这个的库实现 在OpenCV中,我们的概念是查找具有4路或8路连接的连接组件。我希望能够做到这一点,然后桥梁之间的差距断开组件,只要翻转只有1个像素将需要这样做。有关示例,请参见下面的图像 两个4路连接的组件,我们可以在其中桥接间隙,使其成为一个4路连接的组件。因此,我可以使用类似于connect4way(max\u bridge\u size=1)的函数来实现这一点 两个4路连接的组件,我们可以在其中桥接间隙,使其成为一个8路连接的组件。使用connect4way(max\u

我想知道是否有这个的库实现

在OpenCV中,我们的概念是查找具有4路或8路连接的连接组件。我希望能够做到这一点,然后桥梁之间的差距断开组件,只要翻转只有1个像素将需要这样做。有关示例,请参见下面的图像

两个4路连接的组件,我们可以在其中桥接间隙,使其成为一个4路连接的组件。因此,我可以使用类似于
connect4way(max\u bridge\u size=1)
的函数来实现这一点

两个4路连接的组件,我们可以在其中桥接间隙,使其成为一个8路连接的组件。使用
connect4way(max\u bridge\u size=1)
会失败,但我可以使用
connect8way(max\u bridge\u size=1)
来实现这一点。


我确实意识到,在很多情况下,没有一种确定的方法来满足我的要求,尤其是
max\u bridge\u size>1
的情况。尽管如此,我还是要问。

我一直在思考这个问题,我认为我已经接近了,但我不确定你到底想要什么,也没有你的代表性形象。你,或者其他人,也许能够完成它

基本思想是用一个唯一的数字标记每个白色斑点的所有像素。然后通过图像查看3x3正方形,并报告其中存在多个唯一邻居的任何像素,即位于两个不同标记斑点旁边的任何像素

#!/usr/bin/env python3

import cv2
import numpy as np
from scipy.ndimage import label, generate_binary_structure, generic_filter

def bridger(P):
    """
    We receive P[0]..P[8] with the pixels in the 3x3 surrounding window.
    We want to identify pixels with two different neighbouring labels plus background.
    Maybe we want to check the centre pixel P[4] is black?
    """
    neighbours = len(np.unique(P)) - 1
    if neighbours > 1:
        return 255
    return 0
    
   
# Load input image
im = cv2.imread('start.png', cv2.IMREAD_GRAYSCALE)

# Threshold to force everything to pure black or white 
_, bw = cv2.threshold(im,0,255,cv2.THRESH_BINARY)
cv2.imwrite('DEBUG-bw.png', bw)

# The default SE (structuring element) is for 4-connectedness, i.e. only pixels North, South, East and West of another are considered connected.
# We want 8-connected, i.e. N, NE, E, SE, S, SW, W, NW, so we need a corresponding SE
SE = generate_binary_structure(2,2)   

# Now run a labelling, or "Connected Components Analysis"
# Each "blob" of connected pixels matching our seed will get assigned a unique number in the new image called "labeled"
labeled, nObjects = label(bw, structure=SE)
cv2.imwrite('DEBUG-labels.png', labeled)
print(f'Objects found: {nObjects}')

# Look for bridging pixels in each 3x3 neighbourhood
result = generic_filter(labeled, bridger, (3,3))

# Save result
cv2.imwrite('result.png', result)
开始图像:

标记图像:

结果图像-以青色显示的像素:


我想你需要一个“形态学闭合”操作。我想你(大部分)是对的:)我没有花时间检查所有的边缘情况,但似乎至少有一种方法可以翻转比我预期的更多的像素。你愿意与我分享一张代表性的图像吗,突出显示可接受/预期桥接像素的标记版本?我认为这可以做到。非常感谢。酷-祝你的项目好运!顺便说一句,我想你也可以用OpenCV做“连接组件”——我只是碰巧以前用过
scipy
版本,并且有一些代码。是的,我通常用OpenCV做