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

如何合并for循环生成的数组?附NumPy/Scipy示例问题

解决方案:获取所有边界数组并合并

1. 获取所有生成的边界数组

原函数仅计算并打印每个区域的边界,未保存结果。只需初始化一个列表,将每个生成的边界数组添加进去,最后返回该列表即可:

import numpy as np
import scipy.ndimage as nd

a = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
              [0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0],
              [0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

def border_selection(inp_array):
    s2 = nd.generate_binary_structure(rank=2, connectivity=2)
    lab, nlab = nd.label(input=inp_array, structure=s2)
    borders = []  # 存储所有边界数组的列表
    for i in range(1, nlab + 1):
        region_i = lab == i
        expanded = nd.binary_dilation(region_i, iterations=1, structure=s2)
        border = np.logical_xor(region_i, expanded)
        borders.append(border)
    return borders

# 获取所有边界数组
all_borders = border_selection(a)

此时all_borders是包含两个边界数组的列表,可通过索引单独访问每个数组(如all_borders[0]、all_borders[1])。

2. 合并所有边界数组为预期输出

要得到所有边界的并集,只需对all_borders列表中的数组执行逻辑或操作(任意数组中该位置为True,结果即为True)。可以用np.logical_or.reduce()或np.any()实现:

# 合并所有边界数组
merged_border = np.logical_or.reduce(all_borders)
# 等价写法:merged_border = np.any(all_borders, axis=0)

# 打印合并后的结果
print(merged_border)

运行后得到的结果与你提供的预期输出完全一致。

整合版函数(直接返回合并后的边界)

如果不需要单独保存每个边界数组,可以直接在函数内完成合并,节省内存:

def merged_border_selection(inp_array):
    s2 = nd.generate_binary_structure(rank=2, connectivity=2)
    lab, nlab = nd.label(input=inp_array, structure=s2)
    merged = np.zeros_like(inp_array, dtype=bool)
    for i in range(1, nlab + 1):
        region_i = lab == i
        expanded = nd.binary_dilation(region_i, iterations=1, structure=s2)
        border = np.logical_xor(region_i, expanded)
        merged = np.logical_or(merged, border)
    return merged

# 直接获取合并后的边界
final_border = merged_border_selection(a)
print(final_border)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:01:22