1. torchvision.utils.save_image
1.1 封装的原函数
@torch.no_grad()
def save_image(
tensor: Union[torch.Tensor, List[torch.Tensor]],
fp: Union[str, pathlib.Path, BinaryIO],
format: Optional[str] = None,
**kwargs,
) -> None:
"""
Save a given Tensor into an image file.
Args:
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``.
fp (string or file object): A filename or a file object
format(Optional): If omitted, the format to use is determined from the filename extension.
If a file object was used instead of a filename, this parameter should always be used.
**kwargs: Other arguments are documented in ``make_grid``.
"""
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
_log_api_usage_once(save_image)
grid = make_grid(tensor, **kwargs)
# Add 0.5 after unnormalizing to [0, 255] to round to the nearest integer
ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
im = Image.fromarray(ndarr)
im.save(fp, format=format)
1.2 调用示例
import torch
import os
import torchvision.utils as tvu
from PIL import Image, __version__ as PILLOW_VERSION
def save_image(img, file_directory):
if not os.path.exists(os.path.dirname(file_directory)):
os.makedirs(os.path.dirname(file_directory))
tvu.save_image(img, file_directory)
1.3 修改重写torchvision.utils.save_image函数
示例1:
import torch
import os
import torchvision.utils as tvu
from PIL import Image, __version__ as PILLOW_VERSION
def save_image_scale(img, file_directory, size):
if not os.path.exists(os.path.dirname(file_directory)):
os.makedirs(os.path.dirname(file_directory))
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
tvu._log_api_usage_once(tvu.save_image)
grid = tvu.make_grid(img)
# Add 0.5 after unnormalizing to [0, 255] to round to the nearest integer
ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1,

最低0.47元/天 解锁文章

2万+

被折叠的 条评论
为什么被折叠?



