首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >只要不超过n个像素就可以连接断开连接的组件

只要不超过n个像素就可以连接断开连接的组件
EN

Stack Overflow用户
提问于 2021-02-08 19:05:31
回答 1查看 211关注 0票数 0

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

在OpenCV中,我们有寻找具有4路或8路连接的连接组件的概念。我希望能够这样做,然后在断开的组件之间架起桥梁,只要翻转一个像素就可以做到这一点。有关示例,请参阅下图

两个4向连接的组件,我们可以在其中弥合差距,使它们成为一个4向连接的组件。所以我可以使用像connect4way(max_bridge_size=1)这样的函数来做到这一点

两个4向连接的组件,我们可以在其中弥合差距,使它们成为一个8向连接的组件。使用connect4way(max_bridge_size=1)会失败,但我可以使用connect8way(max_bridge_size=1)来实现这一点。

我确实意识到,在很多情况下,没有确定性的方法来做我所要求的事情,特别是在max_bridge_size > 1的情况下。尽管如此,我还是要问。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-09 01:25:47

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

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

代码语言:javascript
运行
复制
#!/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)

开始镜像:

带标签的图像:

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66100401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档