Pytorch使用時的小問題

1.PIL&&Tensor &&ndarray

PIL:PIL庫的圖像數據類型
Tensor:Pytorch的數據類型,這裏也可以是圖像數據類型
ndarry:numpy的數據類型

from torchvision.transforms import transforms
from PIL import Image
import cv2

# 顯示圖片
# Image.show()  # PIL RGB
# cv2.imshow()  # numpy.ndarray BGR
# Tensor需要轉換爲PIL或numpy.ndarray纔可已顯示
path = 'Face.jpg'

img_pil = Image.open(path)  # PIL RGB
img_cv2 = cv2.imread(path)  # numpy.ndarray BGR

"""PIL or numpy.ndarray to Tensor"""
img_pil_tensor = transforms.ToTensor()(img_pil)  # Tensor RGB
img_cv2_tensor = transforms.ToTensor()(img_cv2)  # Tensor BGR

"""Tensor or numpy.ndarray to PIL"""
img_tensor_pil = transforms.ToPILImage()(img_pil_tensor)  # PIL RGB
img_cv2_pil = transforms.ToPILImage()(img_cv2)  # PIL BGR

"""PIL or Tensor to numpy.ndarray"""
img_pilTensor_numpy = img_pil_tensor.numpy()  # numpy.ndarray RGB
img_cv2Tensor_numpy = img_cv2_tensor.numpy()  # numpy.ndarray BGR

"""RGB to BGR"""
"""Tensor"""
BGR_index = [2, 1, 0]
BGR = RGB[BGR_index]
"""PIL"""
R, G, B = RGB.split()
BGR = Image.merge('RGB', (B, G, R))
"""numpy.ndarray"""
BGR = cv2.cvtColor(RGB, cv2.COLOR_RGB2BGR)  # cv2
BGR = RGB[:, :, ::-1]  # numpy.ndarray
"""BGR to RGB"""
"""Tensor"""
RGB_index = [2, 1, 0]
RGB = BGR[RGB_index]
"""numpy.ndaaray"""
RGB = cv2.cvtColor(BGR, cv2.COLOR_BGR2RGB)  # cv2
RGB = BGR[:, :, ::-1]  # numpy.ndarray
"""PIL"""
B, G, R = BGR.split()
RGB = Image.merge('RGB', (R, G, B))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章