示例代码:
from torchvision import transforms from PIL import Image img_jpg = Image.open('C:/Users/admin/Desktop/bird.jpg').convert('RGB') # convert()函数,用于不同模式图像之间的转换, # PIL中有九种不同模式,分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F print(img_jpg) # 输出:<PIL.Image.Image image mode=RGB size=500x333 at 0x16ADDF8B948> to_tensor = transforms.ToTensor() img_tensor = to_tensor(img_jpg) # img_tensor的每个通道最大值为1.0,最小值为0 normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # 归一化到[-1, 1],公式是:(x-0.5)/0.5 img_norm = normalize(img_tensor) # img_norm的每个通道最大值为1.0,最小值为-1.0 # transform tensor back to PIL image img_unnorm = img_norm/2 + 0.5 to_PILimage = transforms.ToPILImage() img_restored = to_PILimage(img_unnorm) img_restored.save('C:/Users/admin/Desktop/bird_restored.jpg')
图像: