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

如何用Python实现2D数组的像素级扩展(保持元素相对位置)

需求与现有实现

我需要将尺寸为(25,180)的2D NumPy数组调整为(50,360),要求所有元素保持原有相对位置不变,效果类似图像升分辨率时的像素复制。例如:
原始(2,3)数组:

((1, 3, 6),
 (4, 7, 8))

需扩展为(4,6)数组:

((1, 1, 3, 3, 6, 6),
 (1, 1, 3, 3, 6, 6),
 (4, 4, 7, 7, 8, 8),
 (4, 4, 7, 7, 8, 8))

尝试过resize和reshape方法未达预期,目前已通过循环实现,但希望找到更简洁的内置函数方案。

已实现的循环代码:

import numpy as np
ary = np.array(((1,3,6),(4,7,8)))
aarryy = np.zeros((4,6))
for i in range(len(ary)):
    for j in range(len(ary[i])):
        aarryy[i*2][j*2] = ary[i][j]
        aarryy[i*2][j*2+1] = ary[i][j]
    aarryy[i*2+1] = aarryy[i*2]
简洁实现方案

方法一:使用np.repeat(最直接)

np.repeat支持指定轴方向的重复次数,完全匹配你的需求:

import numpy as np

ary = np.array(((1,3,6),(4,7,8)))
# 先在列方向(轴1)每个元素重复2次,再在行方向(轴0)重复2次
result = ary.repeat(2, axis=1).repeat(2, axis=0)
print(result)

输出:

[[1 1 3 3 6 6]
 [1 1 3 3 6 6]
 [4 4 7 7 8 8]
 [4 4 7 7 8 8]]

针对你的(25,180)转(50,360)场景,重复次数保持2即可(50=25×2,360=180×2)。

方法二:np.tile结合reshape

通过扩展维度后平铺元素,再调整形状:

import numpy as np

ary = np.array(((1,3,6),(4,7,8)))
# 给原数组增加两个维度,每个元素对应(2,2)的块,再平铺后reshape
result = np.tile(ary[:, :, np.newaxis, np.newaxis], (1,1,2,2)).reshape(4,6)
print(result)

此方法与方法一效果完全一致,适合理解维度扩展的逻辑场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:31:56