Search code examples
python-3.xnumpyimage-processingscalescaletransform

How to deform/scale a 3 dimensional numpy array in one dimension?


I would like to deform/scale a three dimensional numpy array in one dimension. I will visualize my problem in 2D:

I have the original image, which is a 2D numpy array:

enter image description here

Then I want to deform/scale it for some factor in dimension 0, or horizontal dimension:

enter image description here

For PIL images, there are a lot of solutions, for example in pytorch, but what if I have a numpy array of shapes (w, h, d) = (288, 288, 468)? I would like to upsample the width with a factor of 1.04, for example, to (299, 288, 468). Each cell contains a normalized number between 0 and 1.

I am not sure, if I am simply not looking for the correct vocabulary, if I try to search online. So also correcting my question would help. Or tell me the mathematical background of this problem, then I can write the code on my own.

Thank you!


Solution

  • Looks like it is as easy as using the torch.nn.functional.interpolate functional from pytorch and choosing 'trilinear' as interpolation mode:

    import torch
    
    PET = torch.tensor(data)
    
    print("Old shape = {}".format(PET.shape))
    
    scale_factor_x = 1.4
    
    # Scaling.
    PET = torch.nn.functional.interpolate(PET.unsqueeze(0).unsqueeze(0),\
     scale_factor=(scale_factor_x, 1, 1), mode='trilinear').squeeze().squeeze()
    
    print("New shape = {}".format(PET.shape))
    

    output:

    >>> Old shape = torch.Size([288, 288, 468])
    >>> New shape = torch.Size([403, 288, 468])
    

    I verified the results by looking at the data, but I can't show them here due to data privacy. Sorry!