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()