为什么torch.nn.Upsample返回乱码图像?是否是使用方式错误?
问题原因
- 核心错误是误用
reshape执行维度位置切换:读入的图像shape为(H, W, C)(高度、宽度、通道数),reshape仅会按内存存储顺序重组张量,不会调整维度的逻辑顺序,直接执行reshape(4, 200, 390)会彻底打乱原图像的像素与通道对应关系,错误在进入上采样操作前就已经产生。 - 上采样完成后再次使用
reshape将(C, H, W)格式的张量转回(H, W, C),会二次破坏像素结构。 - 数值类型适配问题:
nn.Upsample默认输出为浮点类型,matplotlib显示浮点图像要求数值范围为[0, 1],直接输入范围为[0, 255]的浮点张量会出现颜色显示异常。
修正代码
import torch import imageio import torch.nn as nn from matplotlib import pyplot as plt small = imageio.imread('small.png') # shape (200, 390, 4) # 用transpose置换维度到(C, H, W)格式 small_reshaped = small.transpose(2, 0, 1) # shape (4, 200, 390) batch = torch.as_tensor(small_reshaped).unsqueeze(0) # shape (1, 4, 200, 390) # 可自行指定上采样模式,如mode='bilinear'获得更平滑的效果 ups = nn.Upsample((500, 970)) upsampled_batch = ups(batch) # shape (1, 4, 500, 970) # 用permute置换维度回(H, W, C),转uint8适配matplotlib显示 upsampled_small = upsampled_batch[0].permute(1, 2, 0).to(torch.uint8).numpy() # shape (500, 970, 4) plt.subplot(1,2,1) plt.imshow(small) plt.title("输入图像") plt.subplot(1,2,2) plt.imshow(upsampled_small) plt.title("上采样后图像") plt.show()
内容的提问来源于stack exchange,提问作者c0mr4t
相关产品推荐
相关产品推荐

