1.原图

Python使用PIL.image保存图片

1.首先PIL保存图片的时候,图片类型一定要是ndarray类型,不能是tensor类型,否则报错

img=cv2.imread("./epoch034_iter100_target.png")
img1=torch.tensor(img)
image_pil=Image.fromarray(img1)
image_pil.save("./a1.jpg")
print(img.size)

报错,因为img1是torch类型

Python使用PIL.image保存图片

2.tensor转成ndarray类型保存

######----------2-------
img=cv2.imread("./epoch034_iter100_target.png")
img1=torch.tensor(img)
img1=img1.numpy()
image_pil=Image.fromarray(img1)
image_pil.save("./a2.jpg")
print(img.size)

  结果:正常

 

Python使用PIL.image保存图片

结论:

为什么,torch类型保存,转numpy()重新保存会出现这种结果,因为

numpy中array默认的数据格式是int64类型,而torch中tensor默认的数据格式是float32类型。

所以,保存图片的时候一定要转成numpy

3.如果不进行归一化处理,也会报错

在原图的基础上,乘一个0.5,再加一个0.5,报错 ,猜测是值超出了范围

#--------3------
img=cv2.imread("./epoch034_iter100_target.png")
img1=torch.tensor(img)
img2=img1.mul(0.5).add(0.5)
img2=img2.numpy()
image_pil=Image.fromarray(img2)
image_pil.save("./a3.jpg")

Python使用PIL.image保存图片

总结

原文地址:https://blog.csdn.net/qq_41166909/article/details/126528775

相关文章:

  • 2022-12-23
  • 2022-01-21
  • 2021-11-25
  • 2021-06-23
  • 2022-01-28
  • 2021-09-24
  • 2021-12-26
  • 2021-05-26
猜你喜欢
  • 2021-04-29
  • 2021-11-19
  • 2022-12-23
  • 2021-10-07
  • 2022-02-07
  • 2022-12-23
相关资源
相似解决方案