transforms.ToTensor()

"""Convert a PIL Image or ndarray to tensor and scale the values accordingly.

This transform does not support torchscript.

Converts a PIL Image or numpy.ndarray (H x W x C) in the range
[0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]

简单理解就是进行三个操作

1.将输入数据(H x W x C)变为(C x H x W)

2.将图像的像素值从 [0, 255] 范围归一化到 [0.0, 1.0] 范围。方便后续处理

3.将 PIL 图像或 NumPy ndarray 转换为 PyTorch 张量(Tensor)

示例:1.jpg:

from PIL import Image
from torchvision import transforms

# 打开一个图像文件
image = Image.open('1.jpg')

# 创建一个转换操作,只包含 ToTensor()
a= transforms.ToTensor()

# 应用转换操作,将 PIL 图像转换为 PyTorch 张量
tensor_image = a(image)

# 打印转换后的张量
print(tensor_image)

输出:1.彩色图像有RGB3通道,即c=3,此处1:2:3:是自己标记方便理解,

2.范围在 [0.0, 1.0]之间 

3.将图片转换为 PyTorch 张量(Tensor)

tensor([1:[[0.2902, 0.2824, 0.2745,  ..., 0.2784, 0.2824, 0.2824],
         [0.2824, 0.2745, 0.2667,  ..., 0.2745, 0.2784, 0.2784],
         [0.2745, 0.2667, 0.2588,  ..., 0.2706, 0.2745, 0.2745],
         ...,
         [0.5098, 0.4941, 0.4902,  ..., 0.4000, 0.4549, 0.5059],
         [0.5137, 0.5020, 0.4941,  ..., 0.4745, 0.5020, 0.5294],
         [0.5176, 0.5137, 0.5059,  ..., 0.5294, 0.4980, 0.5059]],

       2: [[0.5412, 0.5333, 0.5255,  ..., 0.5294, 0.5333, 0.5333],
         [0.5333, 0.5255, 0.5176,  ..., 0.5255, 0.5294, 0.5294],
         [0.5255, 0.5176, 0.5098,  ..., 0.5216, 0.5255, 0.5255],
         ...,
         [0.6824, 0.6667, 0.6627,  ..., 0.5216, 0.5686, 0.6196],
         [0.6863, 0.6745, 0.6667,  ..., 0.5882, 0.6078, 0.6353],
         [0.6902, 0.6863, 0.6784,  ..., 0.5725, 0.5725, 0.5569]],

       3: [[0.8196, 0.8118, 0.8039,  ..., 0.8078, 0.8118, 0.8118],
         [0.8118, 0.8039, 0.7961,  ..., 0.8039, 0.8078, 0.8078],
         [0.8039, 0.7961, 0.7882,  ..., 0.8000, 0.8039, 0.8039],
         ...,
         [0.8275, 0.8118, 0.8078,  ..., 0.6941, 0.7412, 0.7922],
         [0.8314, 0.8196, 0.8118,  ..., 0.7608, 0.7843, 0.8118],
         [0.8275, 0.8235, 0.8157,  ..., 0.6824, 0.6902, 0.6941]]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值