代码之家  ›  专栏  ›  技术社区  ›  user2290362

Numpy scale 3D阵列

  •  4
  • user2290362  · 技术社区  · 9 年前

    我试图将3D阵列缩放到64x64x64(从更大的非立方体大小),保持纵横比。

    我在这样的2D阵列中也做了同样的事情:

    pad = Input.size[1]-Input.size[0]
    padLeft = math.ceil(pad/2)
    padRight = math.floor(pad/2)
    
    if(pad > 0):
        paddedInput = np.pad(Input, ((0,0), (padLeft,padRight)), 'constant', constant_values=(0,0))
    else:
        paddedInput = np.pad(Input, ((math.fabs(padLeft),math.fabs(padRight)), (0,0)), 'constant', constant_values=(0,0))
    
    Output = misc.imresize(paddedInput,(InputHeight,InputHeight))
    

    有没有一种方法可以在N(=3)个维度上实现同样的目标?

    编辑:我尝试转换为3D:

    pad = np.zeros((3,1))
    pad[0,0] = max(Input.shape) - Input.shape[0]
    pad[1,0] = max(Input.shape) - Input.shape[1]
    pad[2,0] = max(Input.shape) - Input.shape[2]
    
    paddedInput = np.zeros((max(Input.shape),max(Input.shape),max(Input.shape)))
    print(paddedInput.shape)
    
    for dimension in range(0,3):
        padLeft = math.ceil(pad[dimension,0]/2)
        padRight = math.floor(pad[dimension,0]/2)
        if((padLeft > 0) or (padRight > 0)):
            if dimension == 0:
                paddedInput = np.pad(Input, ((padLeft,padRight),(0,0),(0,0)), 'constant', constant_values=0)
            elif dimension == 1:
                paddedInput = np.pad(paddedInput, ((0,0), (padLeft,padRight),(0,0)), 'constant', constant_values=0)
            elif dimension == 2:
                paddedInput = np.pad(paddedInput, ((0,0),(0,0), (padLeft,padRight)), 'constant', constant_values=0)
    print(paddedInput.shape)
    

    这是运行的,但被填充的维度的填充量是它们需要的两倍。。。

    2 回复  |  直到 9 年前
        1
  •  2
  •   mdurant    9 年前

    看看 zoom 在里面 scipy.ndimage 。这里您提供了沿每个轴的缩放因子,而不是最终的立方体大小,但这很容易计算。

    inarr = np.ones((32,32,32))
    outarr = ndimage.zoom(inarr, 2)
    outarr.shape
    (64, 64, 64)
    
        2
  •  2
  •   user2290362    9 年前

    答案是使用pad,然后使用numpy.ndarray.resize():

    pad = np.zeros((3,1))
    pad[0,0] = max(Input.shape) - Input.shape[0]
    pad[1,0] = max(Input.shape) - Input.shape[1]
    pad[2,0] = max(Input.shape) - Input.shape[2]
    
    paddedInput = np.zeros((max(Input.shape),max(Input.shape),max(Input.shape)))
    
    paddedInput = np.pad(Input, ((int(math.ceil(pad[0,0]/2)),
        int(math.floor(pad[0,0]/2))),(int(math.ceil(pad[1,0]/2)),
        int(math.floor(pad[1,0]/2))),(int(math.ceil(pad[2,0]/2)),
        int(math.floor(pad[2,0]/2)))), 'constant', constant_values=0)
    
    paddedInput.resize((64,64,64))
    

    在一行中完成所有填充可以修复任何错误。

    推荐文章