torchvision.utils.save_image

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, 
### 三级标题:`torchvision.utils.save_image` 函数的正确使用方式 `torchvision.utils.save_image` 是 PyTorch 中用于将张量(tensor)保存为图像文件的实用函数。其函数定义如下: ```python torchvision.utils.save_image(tensor, fp, nrow=8, padding=2, normalize=False, range=None, scale_each=False, format=None) ``` 其中,`fp` 是一个必需的参数,表示目标文件路径。如果调用时未提供该参数,会抛出 `TypeError: save_image() missing 1 required positional argument: 'fp'` 错误[^1]。 例如,以下代码展示了如何正确使用 `save_image` 函数: ```python from torchvision.utils import save_image import torch # 创建一个随机图像张量(1张3通道28x28图像) image_tensor = torch.rand(1, 3, 28, 28) # 保存图像到指定路径 save_image(image_tensor, './output/result.png') ``` ### 三级标题:确保文件路径存在以避免 `FileNotFoundError` 如果目标文件路径中的目录尚未创建,调用 `save_image` 时会抛出 `FileNotFoundError`。为避免此类问题,应在调用前确保目录存在。可以使用 `os.makedirs()` 创建所需的目录结构: ```python import os # 确保路径存在 os.makedirs('./output', exist_ok=True) # 保存图像 save_image(image_tensor, './output/result.png') ``` 如果文件路径是动态构造的,建议使用 `os.path.join()` 来拼接路径,以提高代码的兼容性: ```python sample_path = os.path.join('./nighttime/exp', 'result.png') os.makedirs(os.path.dirname(sample_path), exist_ok=True) save_image(image_tensor, sample_path) ``` ### 三级标题:完整示例与常见错误修复 假设用户调用 `save_image` 的方式如下: ```python save_image(denorm(gen.data.cpu()), sample_path, nrow=1, padding=0) ``` 若 `sample_path` 为 `'./nighttime/exp/result.png'`,则应确保 `'./nighttime/exp'` 目录存在。如果目录不存在,应添加以下代码: ```python os.makedirs(os.path.dirname(sample_path), exist_ok=True) ``` 这样可以确保路径存在,从而避免 `FileNotFoundError`。此外,路径拼接应优先使用 `os.path.join()`,以提高代码在不同操作系统上的兼容性。 ### 三级标题:总结与建议 调用 `torchvision.utils.save_image` 时,必须提供有效的文件路径参数 `fp`,并确保该路径对应的目录存在。建议在调用前使用 `os.makedirs()` 创建所需目录结构,以避免因路径缺失导致的异常。此外,路径拼接应优先使用 `os.path.join()`,以提高代码的可移植性和兼容性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值