【Pytorch】--torchvision.transforms.ToTensor

\quad 在使用Pytorch时候,需要导入图片,一般图片的类型都是numpy.ndarray,需要转换成tensor类型,
这时候就要使用torchvision.transforms.ToTensor

1.原理

\quad 参考:Pytorch之深入torchvision.transforms.ToTensor与ToPILImage在这里插入图片描述

2.测试&&结果

import cv2 as cv
from torchvision import transforms

image = cv.imread('tttt.jpg')
trans = transforms.ToTensor()  # creat object
img_tensor = trans(image)  # object call method

print(type(image))
print('image shape:', image.shape)
print('image 第0通道的行数:', image[:, 0, 0].size)
print('image 第0通道的第一个像素值:', image[0, 0, 0])
print('img_tensor shape:', img_tensor.shape)
print('img_tensor 第0维的第一个值:', img_tensor[0, 0, 0])
print('image 第0通道的第一个像素值归1: image[0, 0, 0] / 256 = ', image[0, 0, 0]/256)
<class 'numpy.ndarray'>
image shape: (552, 725, 3)
image 第0通道的行数: 552
image 第0通道的第一个像素值: 227
img_tensor shape: torch.Size([3, 552, 725])
img_tensor 第0维的第一个值: tensor(0.8902)
image 第0通道的第一个像素值归1: image[0, 0, 0] / 256 =  0.88671875

可以看到通过opencv读入了一张图片大小为:(552, 725, 3)
通过调用torchvision.transforms.ToTensor,转化成Tensor形式,此时的维度为[3, 552, 725]
注意此时Tensor中的每个元素都进行了归一操作,即每个元素都属于[0,1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值