【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.****.net/u012343179/article/details/83007296