Search code examples
pytorchtensortorchvision

Rescale Pytorch tensor values (intensity) to stretch in a specific range


I have an image tensor like

import torch
tensor = torch.rand(1,64,44)

which is like a single channel image. I apply gaussian blur to this random image

import torchvision.transforms as T
transform = T.GaussianBlur(kernel_size=(5,5), sigma = (1,2))
blurred_img = transform(tensor)

This tensor's (blurred_img) max value is around 0.75 and min value is around 0.25. How can I stretch this value so that max is around 1 and min is around 0?

I found a technique using skimage.exposure.rescale_intensity() but applying this like,

stretch = skimage.exposure.rescale_intensity(blurred_img, in_range = 'image', out_range = (0,1)) 

yeilds error

TypeError: min() received an invalid combination of arguments - got (out=NoneType, axis=NoneType, ), but expected one of:
* ()
* (name dim, bool keepdim)
    didn't match because some of the keywords were incorrect: out, axis
* (Tensor other)
* (int dim, bool keepdim)
    didn't match because some of the keywords were incorrect: out, axis

I apologise it I'm making a minor mistake but I really need to get around this issue. Any kind of help is appreciated


Solution

  • I don't think skimage and torch work well with eachother, but you can renormalize it yourself:

    blurred_img -= blurred_img.min()
    blurred_img /= blurred_img.max()
    

    This ensures the minimum is at 0, and the maximum at 1.