Torch tensor saves jpg/png images

foreword

It is sometimes necessary to save some feature maps or image output results verified during training.
Go out to play later, don't write the foreword


save_img

This way is simple and rude

from torchvision.utils import save_image

save_image(tensor, path)

pillow.save

First convert to numpy, map back to 0 to 255, then convert to pillow, and finally save the picture

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))

Guess you like

Origin blog.csdn.net/weixin_43850253/article/details/130887705