how to store a cifar-10 tensor to a png file in pytorch,
in the first step, we use get a batch pytorch tensor, the shape of it is (B,C,H,W)
so we should first to change it to numpy
use this code batch_tensor=batch_tensor.cpu().data.numpy()
then change it to dtype=np.uint8 type numpy array
batch_tensor=np.array(batch_tensor,(0,2,3,1))
then we change it to a normal shape (B,H,W,C)
then change it to PIL.Image, afterwards, just save it to your wished data foloder
from PIL import Image as im
from numpy as np
#the function input is the real pytorch tensor
def save_the_image(batch_tensor):
import numpy as np
from PIL import Image as imdef save_the_image(batch_tensor):batch_tensor=batch_tensor.cpu().data.numpy()batch_tensor=np.array(batch_tensor,dtype=np.uint8)batch_tensor=np.transpose(batch_tensor,(0,2,3,1))for index, image in enumerate(batch_tensor):ret_tensor=im.fromarray(image)ret_tensor.save('data/'+str(index)+'.png')
then all is done, enjoy yourself.