Convert and save PytorchTensor to .mat image on GPU in python

I am a beginner in Pytorch and I am stuck on a question for days. I want to save a image which is in Pytorch tensor form as .mat file. I looked but there doesn’t seem to be a direct method on converting Pytoch tensors to .mat file. One possible solution which I found was to convert it to numpy array, but since I am using Nvidia GPU, when I try converting Pytorch tensor to numpy array it gives me this error :

fake_images[0] = fake_images[0].numpy()

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first

Please can you help me with saving Pytorch tensor to .mat file while using GPU.

Thank you so so much in advance!!

You would have to transfer the tensor to the CPU first (and detach it, if necessary), as given in the error message:

x = fake_images[0].detach().cpu().numpy()

To transform the numpy array to a MATLAB mat you should use scipy.io.savemat.

1 Like

Thank you so much for your response. However when I tried this code, i got this error

TypeError: can't assign a numpy.ndarray to a torch.cuda.FloatTensor

Please can you help me in regard to this ? Any help is much appreciated. Thanks in advance

I guess you are trying to assign the numpy array to the tensor itself via:

fake_images[0] = fake_images[0].detach().cpu().numpy()

If that’s the case, assign the numpy array to a new variable as seen in my code:

x = fake_images[0].detach().cpu().numpy()
1 Like