如何将三个同形Numpy 3D数组按指定维度合并为新数组?
问题原因
你的代码中三个循环是顺序执行的,后续赋值会完全覆盖之前的结果:
- 第一个循环将
clahe_slices的所有第一维度切片替换为clahe_slices1的对应内容 - 第二个循环遍历第二维度索引,替换
clahe_slices中对应列的切片,覆盖第一个循环的大部分数据 - 第三个循环遍历第三维度索引,替换
clahe_slices中对应层的所有切片,最终整个数组只剩clahe_slices3的数据
另外注意:原代码中clahe_slices1/clahe_slices2/clahe_slices3被初始化为零数组,这显然不符合“已完成CLAHE处理”的前提,需要先正确生成这三个处理后的数组。
正确实现方案
以下是基于不同整合需求的实现,先补充生成三个处理后数组的代码:
步骤1:生成各维度CLAHE处理后的数组
import numpy as np import nibabel as nib from skimage.exposure import equalize_adapthist def process_dimension_slices(data, dim): """对指定维度的所有切片应用CLAHE""" result = np.zeros_like(data) if dim == 0: for i in range(data.shape[0]): result[i, :, :] = equalize_adapthist(data[i, :, :]) elif dim == 1: for i in range(data.shape[1]): result[:, i, :] = equalize_adapthist(data[:, i, :]) elif dim == 2: for i in range(data.shape[2]): result[:, :, i] = equalize_adapthist(data[:, :, i]) return result # 加载Nifti数据 nifti_img = nib.load(file_path) img_data = nifti_img.get_fdata() # 生成三个维度的处理结果 clahe_slices1 = process_dimension_slices(img_data, dim=0) clahe_slices2 = process_dimension_slices(img_data, dim=1) clahe_slices3 = process_dimension_slices(img_data, dim=2)
步骤2:根据需求整合数组
方案1:元素级融合(例如取平均值)
如果希望将三个数组的对应元素进行融合,直接用numpy数组运算即可:
def merge_clahe_results(s1, s2, s3): return (s1 + s2 + s3) / 3 clahe_slices = merge_clahe_results(clahe_slices1, clahe_slices2, clahe_slices3)
方案2:多维度拼接(生成4D数组)
如果需要保留三个数组的全部数据,将它们拼接为一个4D数组:
def merge_clahe_results(s1, s2, s3): return np.stack([s1, s2, s3], axis=-1) # 输出形状为(240,240,155,3) clahe_slices = merge_clahe_results(clahe_slices1, clahe_slices2, clahe_slices3)
方案3:指定区域替换(各维度切片占据不同区域)
如果需要让不同维度的处理结果占据数组的特定区域,可手动定义替换范围:
def merge_clahe_results(s1, s2, s3): result = np.zeros_like(s1) # 第一维度处理结果占前120层 result[:120, :, :] = s1[:120, :, :] # 第二维度处理结果占中间120列 result[:, 60:180, :] = s2[:, 60:180, :] # 第三维度处理结果占中间55层 result[:, :, 50:105] = s3[:, :, 50:105] return result clahe_slices = merge_clahe_results(clahe_slices1, clahe_slices2, clahe_slices3)
内容的提问来源于stack exchange,提问作者miara so
相关产品推荐
相关产品推荐

