Save numpy as image in pytorch (data type : float32, clipped between [0,1])

Hi there,

is there any way to save a NumPy array as image in pytorch (I would save the numpy and not the tensor) without using OpenCV… (I want to save the NumPy data as an image without multiplying by 255 or adding any other prepro)

Thanks

What exactly do you mean by saving it as an image “in PyTorch”? An image could take several forms:

  • a numpy array
  • a Tensor (pytorch object)
  • a PIL Image object

Are you trying to save an image on disk? Convert a numpy array to a Tensor? Something else?

A little more detail about what you’re trying to accomplish would help us answer.

1 Like

Thanks for your reply.

What I did is I first loaded a subset of images and convert the tensors to NumPy and now I want to save these images on disk in (.png, jpeg) format but without doing any preprocess as the data is float 32 with values between 0 and 1. Using OpenCV for example requires the multiplication of the array values by 255. But I want to save the array as an image on disk without changing any values.

Thanks,

I don’t know if there’s a way to save something as png without multiplying by 255 first, however you don’t need to go through OpenCV, since you can do it through PIL directly:

from PIL import Image
image_numpy = np.random.rand(224, 224, 3)
img = Image.fromarray(np.uint8(255 * image_numpy))  # no opencv required
img.save("file.png")

You can also save the numpy array directly to disk, however your filesystem won’t recognize it as an image (like you can’t open it as a png):

np.save("file.npy", image_numpy)
1 Like