tensor–>numpyimg = img.numpy()
numpy–>tensor
tensor = transforms.ToTensor()
tensor_img = tensor(img)
tensor–>PIL
CHW–>HWCimg = np.transpose(img, (1,2,0))
HWC–>CHWimg = np.transpose(img, (2,0,1))
查看tensor格式图像 tensor–>numpy
img,tar = test_set[0]
print(type(img)) # <class 'torch.Tensor'>
img = img.numpy()
print(type(img)) # <class 'numpy.ndarray'>
print(img.shape) # (3, 32, 32)
img = np.transpose(img, (1,2,0))
print(img.shape) # (32, 32, 3)
# opencv中的颜色通道顺序是BGR而PIL、torch里面的图像颜色通道是RGB
img=cv2.cvtColor(mat,cv2.COLOR_BGR2RGB)
cv2.imshow('image', img)
cv2.waitKey(0)
查看tensor格式图像 tensor–>PIL
from torchvision import transforms
unloader = transforms.ToPILImage()
image = original_tensor.cpu().clone() # clone the tensor
image = image.squeeze(0) # remove the fake batch dimension
image = unloader(image)
image.save('example.jpg')