(from torchvision import transforms as T)
读取库 | 属性 | 尺寸数据 |
---|---|---|
img = Image.open() | img.size | (720, 1160) |
img.resize | img.resize((512,256)).size | (512, 256) |
T.Resize() | T.Resize((400,400))(img).size | (400, 400) |
np.array(img) | .shape | (1160, 720, 3) |
T.ToTensor() | T.ToTensor()(img).size() | torch.Size([3, 1160, 720]) |
需要注意:T.ToTensor(),T.Resize()的参数不同,Resize的参数是一个尺寸元组且img必须是Image读取的图片;ToTensor的img可以是一个np的数组或Image的图片。ToTensor的返回对象有**.size()方法**,而Resize()的返回值是**.size属性**
方法 | 作用 | 例子 |
---|---|---|
T.Compose() | 将T的多个操作按顺序执行 | T.Compose([T.Resize((256, 512)), T.ToTensor( )]) |
T.Resize() | 只修改图片尺寸,不修改通道顺序 | T.Resize((256, 512))(Image_img)注:img should be PIL Image. |
T.ToTensor( ) | 将hwc数据转换为tensor类型,会修改通道成chw | T.ToTensor( )(Image_img) |
Image读取图,size属性是
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
img = Image.open('4.jpg') # 原始图片尺寸h=1160,w=720,c=3
print('Image对象的size:',img.size,) #Image对象的size: (720, 1160)
img_np = np.array(img)
# Image对象转换为np数组后的shape: (1160, 720, 3)
print('Image对象转换为np数组后的shape:',np.array(img).shape)
img_resize = img.resize((512,256))
print('img_resize:',img_resize.size)
transform_x = T.Compose([T.ToTensor( )])
img_transform = T.ToTensor()(img) #transform_x(img)
print('img_transform:',img_transform.size()) #torch.Size([3, 256, 512])
print('np_transform:',np.array(img_transform).shape) # np_transform: (3, 256, 512)
print(T.Resize((256, 512))(img).size) #(512, 256)
print(np.array(T.Resize((256, 512))(img)).shape) #(256, 512, 3)
print(np.array(T.ToTensor()(T.Resize((256, 512))(img))).shape) #(3, 256, 512)
plt.figure()
plt.subplot(1,2,1)
plt.title('img')
plt.imshow(img)
plt.subplot(1,2,2)
plt.title('img_np')
plt.imshow(img_np)
plt.show()
import matplotlib.pyplot as plt
import matplotlib.image as Img
img = Img.imread('4.jpg')
print(img.shape) # (1160, 720, 3)
plt.imshow(img)
plt.colorbar()
plt.show()
import cv2
img = cv2.imread('4.jpg')
print(img.shape) # (1160, 720, 3)
cv2.imshow('img',img)
cv2.waitKey(0)