transform.ToTensor
类原型:
CLASS torchvision.transforms.ToTensor
作用:
转换PIL Image或numpy。Ndarray到张量。此转换不支持torchscript。、
转换PIL Image或numpy。ndarray(高x宽x宽)在范围[0,255]到一torch。如果PIL图像属于其中一种模式(L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1),则形状(C x H x W)的FloatTensor在[0.0,1.0]范围内,或者如果numpy。Ndarray有dtype = np。在其他情况下,张量返回没有缩放
注意:
由于输入图像被缩放为[0.0,1.0],因此在转换目标图像掩码时不应使用此转换
实例程序:
img = Image.open("data/val/Dog/2.jpg")
print("图像的像素矩阵:\n{}".format(np.array(img)) )
totentor = transforms.ToTensor()
img_totentor = totentor(img)
print("图像的张量:\n{}".format(img_totentor))
**运行结果:**对像素值进行了归一化,使值变换到[0,1]之间
图像的像素矩阵:
[[[190 161 129]
[189 160 130]
[194 167 138]
...
[190 164 127]
[176 155 110]
[201 185 152]]
[[180 151 119]
[175 149 116]
[194 169 139]
...
[177 151 114]
[179 158 113]
[203 187 154]]
[[175 149 114]
[180 154 121]
[201 176 146]
...
[176 150 113]
[181 160 115]
[198 182 149]]
图像的张量:
tensor([[[0.7451, 0.7412, 0.7608, ..., 0.7451, 0.6902, 0.7882],
[0.7059, 0.6863, 0.7608, ..., 0.6941, 0.7020, 0.7961],
[0.6863, 0.7059, 0.7882, ..., 0.6902, 0.7098, 0.7765],
...,
[0.7176, 0.7216, 0.7255, ..., 0.8627, 0.8627, 0.8392],
[0.7176, 0.7216, 0.7216, ..., 0.8706, 0.8706, 0.8431],
[0.6980, 0.6980, 0.7020, ..., 0.7843, 0.7843, 0.7843]],
[[0.6314, 0.6275, 0.6549, ..., 0.6431, 0.6078, 0.7255],
[0.5922, 0.5843, 0.6627, ..., 0.5922, 0.6196, 0.7333],
[0.5843, 0.6039, 0.6902, ..., 0.5882, 0.6275, 0.7137],
...,
[0.6824, 0.6863, 0.6902, ..., 0.8275, 0.8235, 0.8078],
[0.6980, 0.7020, 0.7020, ..., 0.8431, 0.8392, 0.8235],
[0.6824, 0.6824, 0.6863, ..., 0.7647, 0.7725, 0.7804]],
[[0.5059, 0.5098, 0.5412, ..., 0.4980, 0.4314, 0.5961],
[0.4667, 0.4549, 0.5451, ..., 0.4471, 0.4431, 0.6039],
[0.4471, 0.4745, 0.5725, ..., 0.4431, 0.4510, 0.5843],
...,
[0.6549, 0.6588, 0.6627, ..., 0.8078, 0.8157, 0.8000],
[0.6824, 0.6863, 0.6863, ..., 0.8196, 0.8275, 0.8118],
[0.6706, 0.6706, 0.6745, ..., 0.7412, 0.7529, 0.7647]]])