You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取分水岭分割后两个区域的交界像素位置

获取分水岭分割区域的交界像素坐标

针对你遇到的问题,这里提供两种直接获取两个区域交界像素坐标的方法,基于你已有的分割结果labels数组:

方法一:通过掩码膨胀与交集提取交界像素

这种方法利用形态学膨胀操作,精准定位两个区域的相邻像素:

import numpy as np  # 补充代码中缺失的numpy导入

# 获取两个目标区域的二进制掩码
region1_mask = labels == 1
region2_mask = labels == 2

# 用3x3结构元素膨胀其中一个区域的掩码,扩大其邻域范围
structuring_element = np.ones((3, 3), dtype=bool)
expanded_region1 = ndi.binary_dilation(region1_mask, structure=structuring_element)

# 膨胀后的区域与另一个区域的交集,即为两个区域的交界像素
interface_mask = np.logical_and(expanded_region1, region2_mask)

# 提取交界像素的坐标(格式为:[行, 列])
interface_coords = np.argwhere(interface_mask)
print("交界像素坐标:")
print(interface_coords)

方法二:利用边界检测函数筛选目标交界

通过find_boundaries先提取所有区域边界,再筛选出仅属于两个目标区域的交界:

from skimage.segmentation import find_boundaries

# 提取分割结果中的所有区域内部边界(排除背景0)
all_boundaries = find_boundaries(labels, mode='inner', background=0)

# 筛选出邻域同时包含两个目标区域的边界像素
interface_mask = np.zeros_like(all_boundaries, dtype=bool)
for (i, j) in np.argwhere(all_boundaries):
    # 获取当前像素的3x3邻域标签
    neighbor_labels = labels[max(0,i-1):min(i+2,labels.shape[0]), max(0,j-1):min(j+2,labels.shape[1])]
    if 1 in neighbor_labels and 2 in neighbor_labels:
        interface_mask[i,j] = True

# 提取交界像素坐标
interface_coords = np.argwhere(interface_mask)
print("交界像素坐标:")
print(interface_coords)

说明

  • 两种方法返回的坐标格式为(行, 列),若需要(x, y)格式,只需交换坐标的列和行即可。
  • 方法一运算效率更高,适合简单的相邻区域场景;方法二更灵活,可适配复杂的多区域交界筛选需求。

内容的提问来源于stack exchange,提问作者Deb S. B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:06:02