图像生成/超分得到的image中有彩色像素块(色彩溢出)解决方案

在这里插入图片描述
参考:python中用uint8计算超出255后怎么还原

这种彩色像素块色彩溢出的现象,简单来说就是:深度学习的图像处理计算中,常常需要在数据增强的ToTensor除以255.0归一化为float(0-1), 但显示和存储的时候,需要乘以255.0再转换为uint8(0-255),但是中间的数值经过一系列运算已经改变,从floatuint8的转换过程容易发生像素值溢出[0,255]转换为uint8之前需要对tensor使用clip截断

def unnormalize_and_convert(frames, mean=[-1.0,-1.0,-1.0], std=[1.0/0.5, 1.0/0.5, 1.0/0.5]):
    """
    Unnormalizes the given frames and converts them to uint8 numpy array for video saving.

    Parameters:
    - frames (torch.Tensor): The frames to unnormalize, shape should be (C, T, H, W).
    - mean (list or torch.Tensor): The mean values for each channel for normalization.
    - std (list or torch.Tensor): The standard deviation values for each channel for normalization.

    Returns:
    - video (numpy.ndarray): Unnormalized frames as a uint8 numpy array, shape should be (T, H, W, C).
    """
    # Calculate the unnormalize mean and std
    unnormalize_mean = [-m / s for m, s in zip(mean, std)]
    unnormalize_std = [1 / s for s in std]
    # Define the unnormalize transform
    unnormalize = transforms.Normalize(mean=unnormalize_mean, std=unnormalize_std)
    # Permute frames to (T, C, H, W), clone and detach to avoid modifying the original tensor
    frame_list = [unnormalize(frame) for frame in frames.permute(1, 0, 2, 3).clone().detach().cpu().float()]
    # Stack and permute back to (C, T, H, W)
    frames_unnorm = torch.stack(frame_list, dim=0).permute(1, 0, 2, 3)
    # Convert to numpy, permute to (T, H, W, C)
    video = frames_unnorm.permute(1, 2, 3, 0).detach().cpu().numpy()
    # Scale [0,1] float to [0, 255] uint8 and clip
    video = (video * 255.0).clip(0, 255).astype('uint8')

    return video
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yuezero_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值