如何在python中插入2D数组

2024-05-15 15:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用numpy.interp插值2个数组,但得到了ValueError:object对于所需的数组来说太深了。 我正在做的是从Matlab中的一段代码转换成Python。 这是我的Matlab代码:

ops = oldpixsize; 
nps = newpixsize; 
ss  = ops/2; nn  = nps/2;

% create the meshes for old and new image 
[Ox,Oy] = meshgrid(ss(1):ops(1):c*ops(1)+ss(1),...
                  ss(2):ops(2):r*ops(2)+ss(2));
[Nx,Ny] = meshgrid(nn(1):nps(1):c*ops(1)+nn(1),...
                  nn(2):nps(2):r*ops(2)+nn(2)); 
%create the new image z > 1 for multispectral images 
%(e.g. z = 3 RGB color images) 
for i=1:z
   nimg(:,:,i) = interp2(Ox,Oy,img(:,:,i),Nx,Ny,intmethod); 
end

我注意到,与Matlab不同,Python没有使用必要的维度转换生成的数组以放置所有插值值,这是我的Python代码:

source = "multi_rgb.tif"
driverTiff = gdal.GetDriverByName("GTiff")
new_multi = gdal.Open(source)
info_multi = gdal.Info(new_multi)

old_pixel = 4
new_pixel = 1
old_size = np.array([old_pixel,old_pixel]).astype(np.float32)
new_size = np.array([new_pixel,new_pixel]).astype(np.float32)

metod = 'nearest'

f = new_multi.RasterYSize-1
c = new_multi.RasterXSize-1
bands = new_multi.RasterCount
o_s = old_size / 2
n_s = new_size / 2

ox = np.arange(o_s[0],c*old_size[0]+old_size[0],old_size[0])
oy = np.arange(o_s[1],f*old_size[1]+old_size[1],old_size[1])
nx = np.arange(n_s[0],c*old_size[0]+new_size[0],new_size[0])
ny = np.arange(n_s[0],f*old_size[0]+new_size[0],new_size[0])
[Ox,Oy] = np.meshgrid(ox,oy)
[Nx,Ny] = np.meshgrid(nx,ny)

i=0
band_list = []
for i in range(1,bands+1):
    band = new_multi.GetRasterBand(i).ReadAsArray().astype(np.uint8)
    band_list.append(band)
    i = i+1
old_imagen = np.stack((band_list),axis = 2)

for i in range(1,b+1):
    print("entro al for N.",i)
    new_imagen[:,:,i] = np.interp(Ox,Oy,old_imagen[:,:,i],Nx,Ny)

但当我运行它时,我得到了一个错误:对象对于所需的数组来说太深了。 我能做什么


Tags: newforsizebandnpnn数组multi