Python學習記錄(五):圖像讀取

一、OpenCV圖像讀取

import cv2

image = cv2.imread(image_path)
# print(image.shape) # [H, W, C]
cv2.imshow("window1", image)
cv2.waitKey(0)

opencv-python cv2.imread()讀取的圖像類型是np.ndarry類型

二、PIL(Pillow)圖像讀取

from PIL import Image

image = Image.open(image_path)
image_np = np.array(image, dtype=np.float32) / 255.0
image_np = cv2.resize(image_np, (200, 200)) # resize
input = torch.from_numpy(image).unsqueeze(0).permute(0, 3, 1, 2)
print(input.size())

Image.open()讀取圖像文件後,轉爲np.ndarray的格式

三、np.numpy與torch.Tensor相互轉換

3.1 np.ndarray轉torch.tensor

  • torch.from_numpy()
  • torch.Tensor()

https://researchdatapod.com/how-to-convert-numpy-array-to-pytorch-tensor

3.2 torch.tensor轉np.ndarray

def tocpu(x):
  return x.detach().cpu().numpy().copy()

四、base64

import base64
with open("my_image.jpg", "rb") as img_file:
    my_string = base64.b64encode(img_file.read())
print(my_string)

https://www.codespeedy.com/convert-image-to-base64-string-in-python/

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