torchvision 笔记:ToTensor()

Posted UQI-LIUWJ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了torchvision 笔记:ToTensor()相关的知识,希望对你有一定的参考价值。

1 ToTensor

shape(H, W, C)numpy.ndarrayimg转为shape(C, H, W)tensor

在一定条件下,将每一个数值归一化到[0,1],归一化方法比较简单,直接除以255即可。(一定条件后面会说明)

1.1 Ndarray

只有Ndarray是np.uint8 类型的时候,才会归一化

1.1.1 np.uint8 类型

看得出来确实归一化了

import torchvision.transforms as transforms
import numpy as np

a=np.array([[100,200],
                [400,500],
                [700,800]],dtype=np.uint8)

a=a.reshape(3,2,1)
a.shape
#(3, 2, 1)


t=transforms.ToTensor()
ta=t(a)
print(a)
'''
[[[100]
  [200]]

 [[144]
  [244]]

 [[188]
'''

print(ta)
'''
tensor([[[0.3922, 0.7843],
         [0.5647, 0.9569],
         [0.7373, 0.1255]]])
'''

print(ta.shape)
#torch.Size([1, 3, 2])

1.1.2 非np.uint8 类型

没有归一化

import torchvision.transforms as transforms
import numpy as np

a=np.array([[100,200],
                [400,500],
                [700,800]],dtype=np.uint8)

a=a.reshape(3,2,1)
a.shape,a.dtype
((3, 2, 1), dtype('int32'))


t=transforms.ToTensor()
ta=t(a)
print(a)
'''
[[[100]
  [200]]

 [[144]
  [244]]

 [[188]
'''

print(ta)
'''
tensor([[[100, 200],
         [400, 500],
         [700, 800]]], dtype=torch.int32)
'''

print(ta.shape)
#torch.Size([1, 3, 2])

1.2 图片

以DeepFasion数据集里面的一张图片为例:

from PIL import Image
from torchvision import transforms, utils
a=Image.open(b+'img/00000.jpg')
a

 

y=transforms.ToTensor()
a=y(a)
a
'''
tensor([[[0.9255, 0.9255, 0.9255,  ..., 0.9176, 0.9176, 0.9176],
         [0.9255, 0.9255, 0.9255,  ..., 0.9176, 0.9176, 0.9176],
         [0.9255, 0.9255, 0.9255,  ..., 0.9176, 0.9176, 0.9176],
         ...,
         [0.7882, 0.7882, 0.7882,  ..., 0.7922, 0.7922, 0.7922],
         [0.7882, 0.7882, 0.7882,  ..., 0.7922, 0.7922, 0.7922],
         [0.7882, 0.7882, 0.7882,  ..., 0.7922, 0.7922, 0.7922]],

        [[0.9255, 0.9255, 0.9255,  ..., 0.9216, 0.9216, 0.9216],
         [0.9255, 0.9255, 0.9255,  ..., 0.9216, 0.9216, 0.9216],
         [0.9255, 0.9255, 0.9255,  ..., 0.9216, 0.9216, 0.9216],
         ...,
         [0.7961, 0.7961, 0.7961,  ..., 0.7922, 0.7922, 0.7922],
         [0.7961, 0.7961, 0.7961,  ..., 0.7922, 0.7922, 0.7922],
         [0.7961, 0.7961, 0.7961,  ..., 0.7922, 0.7922, 0.7922]],

        [[0.9255, 0.9255, 0.9255,  ..., 0.9294, 0.9294, 0.9294],
         [0.9255, 0.9255, 0.9255,  ..., 0.9294, 0.9294, 0.9294],
         [0.9255, 0.9255, 0.9255,  ..., 0.9294, 0.9294, 0.9294],
         ...,
         [0.7922, 0.7922, 0.7922,  ..., 0.8000, 0.8000, 0.8000],
         [0.7922, 0.7922, 0.7922,  ..., 0.8000, 0.8000, 0.8000],
         [0.7922, 0.7922, 0.7922,  ..., 0.8000, 0.8000, 0.8000]]])
'''

以上是关于torchvision 笔记:ToTensor()的主要内容,如果未能解决你的问题,请参考以下文章

PyTorch学习笔记——图像处理(transforms.Normalize 归一化)

pytorch 笔记:DataLoader 扩展:构造图片DataLoader

PyTorch实现手写数字识别

pytorch/torchvision处理32位/16位灰度图的坑

Pytorch学习

Pytorch学习