【Pytorch】torchvision.utils.save_image直接保存tensor为图片

一般来说,需要将tensor转变为numpy类型的数组从而保存图片,这样的过程比较繁琐,Pytorch提供了save_image()函数,可直接将tensor保存为图片,若tensor在cuda上也会移到CPU中进行保存。

在这里插入图片描述)
参数:

  • tensor (Tensor or list): Image to be saved. If given a mini-batch tensor, saves the tensor as a grid of images by calling make_grid.
  • **kwargs: Other arguments are documented in make_grid.

其中从第三个参数开始为函数make_grid()的参数。
根据官方文档的描述,make_grid()函数主要用于生成雪碧图,何为雪碧图(sprite image)?即由很多张小图片组成的一张大图。如下图所示。
在这里插入图片描述

再来看看make_grid()函数的参数。
在这里插入图片描述

  • tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)or a list of images all of the same size.
  • nrow (int, optional): Number of images displayed in each row of the grid.The final grid size is (B / nrow, nrow). Default: 8.
  • padding (int, optional): amount of padding. Default: 2.
  • normalize (bool, optional): If True, shift the image to the range (0, 1),by the min and max values specified by :attr:range. Default: False.
  • range (tuple, optional): tuple (min, max) where min and max are numbers, then these numbers are used to normalize the image. By default, min and max are computed from the tensor.
  • scale_each (bool, optional): If True, scale each image in the batch of images separately rather than the (min, max) over all images. Default: False.
  • pad_value (float, optional): Value for the padded pixels. Default: 0.

其中,nrow为大图片中每行所包含的小图片的个数,默认为8个,得到的大图片的形状为(B / nrow, nrow)。

通过参数,可对生成的雪碧图设置行列数、小图片间间距、是否标准化、规格化、是否进行缩放以及填充像素值。

结论:torchvision.utils包中提供了save_image()函数可以很方便的将tensor数据保存为图片,其中如果tensor由很多小图片组成,则会自动调用make_grid()函数将小图片拼接为大图片再保存。

参考:
https://pytorch-cn.readthedocs.io/zh/latest/torchvision/torchvision-utils/
https://blog.csdn.net/u012343179/article/details/83007296

  • 17
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值