torchvision.transforms模块包含了图像转换函数,这些函数可以作用于PIL对象和Tensor对象。PyTorch里面使用PIL很多,而且torchvision用PIL作为默认的后端
PIL默认为torchvision的后端参考:《 Why is PIL used so often with Pytorch》--- PIL比OpenCV更加轻量化和效率高。《Python PIL 模块 vs OpenCV模块比较》
- PILToTensor()是把PIL Image对象转换为PyTorch Tensor对象,数据类型不变;
- ToTensor()是把取值为 [0, 255] 的PIL Image 或 numpy.ndarray 为取值为 [0.0, 1.0] 的PyTorch Tensor对象,注意:因为输入图像被缩放到 [0.0, 1.0],所以在变换目标图像掩码时不应使用此变换。
范例:
# Import necessary libraries
import torch
from PIL import Image
import cv2
import torchvision.transforms as transforms
# Read a PIL image
image = Image.open('iceland.jpg')
# Define a transform to convert PIL
# image to a Torch tensor
transform = transforms.Compose([
transforms.PILToTensor()
])
# transform = transforms.PILToTensor()
# Convert the PIL image to Torch tensor
img_tensor = transform(image)
# print the converted Torch tensor
print(img_tensor.shape)
print(img_tensor)
# Read the image by OpenCV
image = cv2.imread('iceland.jpg')
# Convert BGR image to RGB image
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Define a transform to convert
# the image to torch tensor
transform = transforms.Compose([
transforms.ToTensor()
])
# Convert the image to Torch tensor
tensor = transform(image)
# print the converted image tensor
print(tensor.shape)
print(tensor)
运行结果
测试图片如下: iceland.jpg
网友评论