pytorch学习(三)—图像的加载/读取方式

import matplotlib.pyplot as plt
import skimage.io as io
import cv2
from PIL import Image
import numpy as np
import torch

#使用Skimage读取图像
# skimage.io imread()-----np.ndarray,  (H x W x C), [0, 255],RGB
img_skimage = io.imread('./data/dog.jpg')
print(img_skimage.shape)

#使用opencv读取图像
# cv2.imread()------np.array, (H x W xC), [0, 255], BGR
img_cv = cv2.imread('./data/dog.jpg')
print(img_cv.shape)

#使用PIL读取图像
# (H x W x C), [0, 255], RGB
img_PIL = Image.open('./data/dog.jpg')
img_PIL_l = np.array(img_PIL)
print(img_PIL_l.shape)

plt.figure()
for i, im in enumerate([img_skimage,img_cv,img_PIL_l]):
    ax = plt.subplot(1,3,i + 1)
    ax.imshow(im)
    #plt.pause(0.01)
    
 
# ------------np.ndarray转为torch.Tensor------------------------------------
# numpy image: H x W x C  (0,1,2)
# torch image: C x H x W  (2,0,1)
# np.transpose( xxx,  (2, 0, 1))   # 将 H x W x C 转化为 C x H x W
tensor_skimage = torch.from_numpy(np.transpose(img_skimage,(2,0,1)))
print(tensor_skimage.shape)
tensor_cv = torch.from_numpy(np.transpose(img_cv,(2,0,1)))
print(tensor_cv.shape)
tensor_pil = torch.from_numpy(np.transpose(img_PIL_l,(2,0,1)))
print(tensor_pil.shape)

#plt只支持数组对象
#ax.imshow(im),im可以是数列类格式、或者PIL图片。
'''
plt.figure()
for i, img in enumerate([tensor_skimage,tensor_cv,tensor_pil]):
    ax = plt.subplot(1,3,i + 1)
    ax.imshow(img)
''' 

# np.transpose( xxx,  (2, 0, 1))   # 将 C x H x W 转化为 H x W x C
img_skimage_2 = np.transpose(tensor_skimage.numpy(), (1, 2, 0))
print(img_skimage_2.shape)
img_cv_2 = np.transpose(tensor_cv.numpy(), (1, 2, 0))
print(img_cv_2.shape)
img_pil_2 = np.transpose(tensor_pil.numpy(), (1, 2, 0))
print(img_pil_2.shape)
plt.figure()
for i, im in enumerate([img_skimage_2, img_cv_2, img_pil_2]):
    ax = plt.subplot(1, 3, i + 1)
    ax.imshow(im)
    
    
#opencv读取的图像为BGR,首先需要转为RGB
img_cv = cv2.cvtColor(img_cv,cv2.COLOR_BGR2RGB)

#转torch.Tensor
tensor_cv = torch.from_numpy(img_cv)

#tensor转numpy
numpy_cv = tensor_cv.numpy()

plt.figure()
plt.title("cv")
plt.imshow(numpy_cv)
plt.show()

 

你可能感兴趣的:(pytorch,python)