torch tensor保存jpg/png图片

前言

就是有时候需要保存一些feature map或者训练过程中验证的图像输出结果。
待会儿出去玩,先不写前言


save_img

这种方式简单粗暴

from torchvision.utils import save_image

save_image(tensor, path)

pillow.save

先转成numpy, 映射回0到255, 然后再转成pillow, 最后保存图片

def save_batch_img(batch_img, output_dir, prefix=None):
    """
    img: tensor, [b, c, h, w] , [0, 1]
    """
    for i in range(batch_img.shape[0]):
        img = batch_img[i]
        img = img.permute(1, 2, 0) # shape HWC
        img = img.detach().cpu().numpy()
        img = (img * 255).astype(np.uint8)
        img = Image.fromarray(img)

        # # 保存图像
        os.makedirs(output_dir, exist_ok=True)
        if prefix is not None:
            img.save('{}/{}_{}.jpg'.format(output_dir, prefix, i))
        else:
            img.save('{}/{}.jpg'.format(output_dir, i))

猜你喜欢

转载自blog.csdn.net/weixin_43850253/article/details/130887705
今日推荐