简体   繁体   English

Numpy scale 3D阵列

[英]Numpy scale 3D array

I'm trying to scale a 3D array to size 64x64x64 (from a larger, non cube size), keeping aspect ratio. 我正在尝试将3D阵列缩放到64x64x64(从更大的非立方体大小),保持纵横比。

I've done the same thing in a 2D array like this: 我在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))

Is there a way to achieve the same thing in N (=3) dimensions? 有没有办法在N(= 3)维度中实现相同的目标?

Edit: My attempt at conversion to 3D: 编辑:我尝试转换为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)

This runs but the dimensions that get padded are padded with double the amount they need to be... 这样运行,但填充的尺寸填充了他们需要的两倍...

Take a look at zoom in scipy.ndimage . 看一下放大 scipy.ndimage Here you provide zooming factors along each axis, rather than final cube size, but that is simple to figure out. 在这里,您可以提供沿每个轴的缩放因子,而不是最终的立方体大小,但这很容易理解。

inarr = np.ones((32,32,32))
outarr = ndimage.zoom(inarr, 2)
outarr.shape
(64, 64, 64)

The answer is to use pad and then numpy.ndarray.resize() : 答案是使用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))

Doing the pad all on one line fixes any errors there were. 在一行上完成所有填充都可以修复任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM