如何将transforms.Normalize()后的tensor还原
时间: 2024-05-14 15:11:53 浏览: 174
transforms.zip
将正态化后的张量还原为原始张量,需要执行以下步骤:
1. 计算每个通道的反标准化参数,即:
```
mean = [-0.485/0.229, -0.456/0.224, -0.406/0.225]
std = [1/0.229, 1/0.224, 1/0.225]
```
请注意,这里使用的是transforms.Normalize()的默认参数。
2. 对每个通道的像素值执行反标准化,即:
```
pixel = pixel * std[channel_index] + mean[channel_index]
```
3. 将所有通道的像素值组合成一个张量。
完整的代码示例:
```python
import torch
import torchvision.transforms as transforms
# 假设原始张量是img,且已经通过transforms.Normalize()标准化过
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
img_norm = normalize(img)
# 反标准化
mean = [-0.485/0.229, -0.456/0.224, -0.406/0.225]
std = [1/0.229, 1/0.224, 1/0.225]
img = torch.zeros_like(img_norm)
for i in range(3):
img[:, :, i] = img_norm[:, :, i] * std[i] + mean[i]
```
阅读全文