You need to enable JavaScript to run this app. 如何用Python实现二值图像指定像素的4/8连通路径提取
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现二值图像指定像素的4/8连通路径提取

二值图像指定像素连通区域提取的Python实现方案

1. 基于scipy内置连通域分析(推荐)

这是工程实践里最常用的实现方式,不需要手动写遍历逻辑,性能由底层C实现保障,是最Pythonic的写法,大尺寸图像下运行效率远高于纯Python脚本。
核心用到scipy.ndimage的两个能力:

  • generate_binary_structure:根据输入维度和连通范围,自动生成对应邻接规则的结构矩阵
    • 传入参数2,1生成十字形结构,对应4邻接规则
    • 传入参数2,2生成全3*3邻域结构,对应8邻接规则
  • label:对二值图做全图连通域标记,输入自定义的邻接结构矩阵即可适配不同连通规则

实现代码示例:

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

def extract_connected_region(binary_img, x, y, connectivity=4):
    # 适配1起始的坐标输入:numpy数组为(行, 列)索引,即(y, x)顺序
    row_idx = y - 1
    col_idx = x - 1
    height, width = binary_img.shape
    
    # 检查坐标越界、起点本身为False的情况
    if not (0 <= row_idx < height and 0 <= col_idx < width) or not binary_img[row_idx, col_idx]:
        return np.zeros_like(binary_img, dtype=bool)
    
    # 生成对应邻接规则的结构
    if connectivity == 4:
        struct = generate_binary_structure(2, 1)
    elif connectivity == 8:
        struct = generate_binary_structure(2, 2)
    else:
        raise ValueError("仅支持4邻接、8邻接两种连通规则")
    
    # 标记全图连通域
    labeled_map, _ = label(binary_img, structure=struct)
    # 提取起点所在的连通域
    target_region_id = labeled_map[row_idx, col_idx]
    return labeled_map == target_region_id

用题目给出的测试用例验证:

# 题目给出的输入二值图
test_img = np.array([
    [True, False, False, False],
    [False, True, True, True],
    [False, True, True, False]
])

# 测试用例1:坐标(1,1)的4连通结果
extract_connected_region(test_img, x=1, y=1, connectivity=4)
# 输出和题目给出的预期完全一致:仅左上角位置为True,其余全为False

# 测试用例2:坐标(3,2)的4连通结果
extract_connected_region(test_img, x=3, y=2, connectivity=4)
# 输出和题目给出的预期完全一致:所有连通的像素全部标记为True

2. 纯Python实现的BFS/DFS遍历(无第三方依赖)

如果运行环境不方便安装scipy,可以手动实现广度/深度优先遍历逻辑,核心思路非常直观:

  • 从给定的起点位置出发,按照对应邻接规则,遍历所有和起点连通、且在输入二值图中值为True的像素
  • 4邻接对应的偏移量为上下左右4个方向,8邻接对应所有斜向+上下左右共8个方向

实现代码示例:

from collections import deque

def extract_connected_region_native(binary_img, x, y, connectivity=4):
    height, width = binary_img.shape
    row_idx = y -1
    col_idx = x -1

    # 边界和合法性检查
    if not (0 <= row_idx < height and 0 <= col_idx < width) or not binary_img[row_idx, col_idx]:
        return np.zeros_like(binary_img, dtype=bool)
    
    # 邻接偏移量定义
    if connectivity == 4:
        neighbor_offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    else:
        neighbor_offsets = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
    
    # 初始化访问标记矩阵
    visited = np.zeros_like(binary_img, dtype=bool)
    # 用队列做BFS,替换成栈就是DFS
    dq = deque()
    dq.append((row_idx, col_idx))
    visited[row_idx, col_idx] = True

    while dq:
        cur_row, cur_col = dq.popleft()
        for dr, dc in neighbor_offsets:
            next_row = cur_row + dr
            next_col = cur_col + dc
            # 检查下一个点是否在边界内、未访问过、属于输入图的True像素
            if (0 <= next_row < height and 0 <= next_col < width 
                and not visited[next_row, next_col] 
                and binary_img[next_row, next_col]):
                visited[next_row, next_col] = True
                dq.append((next_row, next_col))
    return visited

这种实现的特点是没有额外依赖,适合轻量化场景,但大尺寸图像的运行效率远低于scipy的底层实现。

常见注意点

  • 坐标顺序适配:numpy数组的索引顺序是[行, 列],也就是对应坐标里的y, x,很容易搞反导致连通域定位错误,所有实现里最好统一做1起始坐标到0起始数组索引的转换
  • 起点合法性判断:如果给定坐标的位置在输入二值图里本身就是False,按照规则应该直接返回全False的结果,不要强行从False位置开始遍历
  • 邻接规则匹配:不要在需要4邻接的场景下误用8邻接的偏移量,会导致连通域范围比预期大很多

内容的提问来源于stack exchange,提问作者lowlypalace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 03:27:03