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

Python如何将多个128x128数组/图像拼接为指定维度的numpy数组

实现方案

你可以通过以下几种方法得到目标维度的数组:

  • 方法1:直接调整现有数组的轴位置
    对已经生成的shape为(3, 2, 128, 128)的数组,用np.moveaxis把第二个维度(索引为1)移动到最后一位即可:
    X = np.moveaxis(X, source=1, destination=-1)
    print(X.shape) # 输出 (3, 128, 128, 2)
    
  • 方法2:堆叠数组时直接指定轴顺序,避免后续调整
    堆叠每组2张128x128的图像时,就指定沿最后一维拼接,再堆叠三个分组即可:
    import numpy as np
    a1 = np.random.rand(128,128)
    a2 = np.random.rand(128,128)
    b1 = np.random.rand(128,128)
    b2 = np.random.rand(128,128)
    c1 = np.random.rand(128,128)
    c2 =np.random.rand(128,128)
    
    # 单组内沿最后一维堆叠,得到(128,128,2)的数组
    X1 = np.stack([a1, a2], axis=-1)
    X2 = np.stack([b1, b2], axis=-1)
    X3 = np.stack([c1, c2], axis=-1)
    
    # 沿第一维堆叠三个分组,直接得到目标维度
    X = np.stack([X1, X2, X3], axis=0)
    print(X.shape) # 输出 (3, 128, 128, 2)
    
  • 方法3:用transpose直接重排轴顺序
    对已有的数组,直接指定新的轴顺序即可:
    X = X.transpose(0, 2, 3, 1)
    print(X.shape) # 输出 (3, 128, 128, 2)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:36:03