-
为什么 tensor 的数值在 0-1 范围内?
当你用 torchvision.transforms.ToTensor() 处理图片时,原始图片的像素值(通常是 0~255 的整数)会被除以 255,变成 0~1 之间的浮点数。
这样做的目的是为了让神经网络训练时数值更稳定,便于归一化和梯度传播。 -
为什么用 matplotlib 显示时,图片看起来还是“正常”的?
matplotlib.pyplot.imshow() 可以自动识别输入数据的范围:
如果输入是 0~1 的浮点数,imshow 会把 0 显示为黑,1 显示为白(或彩色图的最大值),中间值线性映射为灰度或颜色。
如果输入是 0~255 的整数,imshow 也会自动映射到显示色彩。
所以只要数据的相对比例没变,显示出来的图片视觉效果是一样的。
import matplotlib.pyplot as plt
import numpy as np
# 假设原始图片像素
img_uint8 = np.array([[0, 128, 255]], dtype=np.uint8) # 0~255
img_float = img_uint8 / 255.0 # 0~1
plt.subplot(1,2,1)
plt.title('uint8')
plt.imshow(img_uint8, cmap='gray', vmin=0, vmax=255)
plt.subplot(1,2,2)
plt.title('float')
plt.imshow(img_float, cmap='gray', vmin=0, vmax=1)
plt.show()