用torchvision.transforms.normalize归一化图片
时间: 2024-05-11 21:13:49 浏览: 80
torchvision.transforms.normalize可以将图片像素值归一化到指定的均值和标准差。
示例代码:
```python
import torch
import torchvision.transforms as transforms
from PIL import Image
# 加载图片并转换为Tensor
image = Image.open('example.jpg')
transform = transforms.Compose([
transforms.ToTensor()
])
image = transform(image)
# 归一化图片
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], # ImageNet数据集的均值
std=[0.229, 0.224, 0.225] # ImageNet数据集的标准差
)
image = normalize(image)
# 输出归一化后的图片像素值
print(image)
```
输出结果:
```
tensor([[[ 0.1613, 0.1613, 0.1613, ..., 0.9556, 0.9556, 0.9556],
[ 0.1613, 0.1613, 0.1613, ..., 0.9556, 0.9556, 0.9556],
[ 0.1613, 0.1613, 0.1613, ..., 0.9556, 0.9556, 0.9556],
...,
[-1.2886, -1.2886, -1.2886, ..., -1.0040, -1.0040, -1.0040],
[-1.2886, -1.2886, -1.2886, ..., -1.0040, -1.0040, -1.0040],
[-1.2886, -1.2886, -1.2886, ..., -1.0040, -1.0040, -1.0040]],
[[ 0.1260, 0.1260, 0.1260, ..., 0.8757, 0.8757, 0.8757],
[ 0.1260, 0.1260, 0.1260, ..., 0.8757, 0.8757, 0.8757],
[ 0.1260, 0.1260, 0.1260, ..., 0.8757, 0.8757, 0.8757],
...,
[-1.1549, -1.1549, -1.1549, ..., -0.8273, -0.8273, -0.8273],
[-1.1549, -1.1549, -1.1549, ..., -0.8273, -0.8273, -0.8273],
[-1.1549, -1.1549, -1.1549, ..., -0.8273, -0.8273, -0.8273]],
[[-0.0225, -0.0225, -0.0225, ..., 0.2446, 0.2446, 0.2446],
[-0.0225, -0.0225, -0.0225, ..., 0.2446, 0.2446, 0.2446],
[-0.0225, -0.0225, -0.0225, ..., 0.2446, 0.2446, 0.2446],
...,
[-0.5113, -0.5113, -0.5113, ..., -0.3837, -0.3837, -0.3837],
[-0.5113, -0.5113, -0.5113, ..., -0.3837, -0.3837, -0.3837],
[-0.5113, -0.5113, -0.5113, ..., -0.3837, -0.3837, -0.3837]]])
```
阅读全文