opencv PIL SummaryWriter读写图片的形状和顺序

pip install opencv-python
pip install tensorboard

cv2读入形状为HWC,顺序BGR,range[0, 255]
PIL.Image读入形状为HWC,顺序RGB,range[0, 255]
SummaryWriter.add_image默认写入形状为CHW(可指定参数dataformats=“HWC”),顺序RGB,若传入numpy格式要求range[0, 255],若传入tensor格式要求range[0.0, 1.0]

transforms.ToTensor()
可以将
shape HWC range[0, 255] 的 numpy或PIL Image
转换为
shape CHW range[0.0, 1.0] 的 tensor
(但这不会修改颜色顺序,所以对于从opencv读向SummaryWriter.add_image写,使用cv2.cvtColor(…, cv2.COLOR_BGR2RGB)将顺序BGR修改为RGB)

import torch
from PIL import Image
import numpy as np
import cv2
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms

writer = SummaryWriter("test_logs")

img_path = "test.jpg"

# -------------------- 传入numpy格式 range[0, 255]
# cv2读入
img1 = cv2.imread(img_path)
# BGR->RGB
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
# 以默认CHW格式写入
writer.add_image("test", np.transpose(img1, (2, 0, 1)), 1)
# 指定格式为HWC
writer.add_image("test", img1, 2, dataformats="HWC")


# PIL.Image读入
img2 = Image.open(img_path)
img2 = np.array(img2)
# 以默认CHW格式写入
writer.add_image("test", np.transpose(img2, (2, 0, 1)), 3)
# 指定格式为HWC
writer.add_image("test", img2, 4, dataformats="HWC")


# -------------------- 传入tensor格式 range[0.0, 1.0]
# cv2读入
img1 = cv2.imread(img_path)
# BGR->RGB
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)

img1_tensor = torch.tensor(img1, dtype=torch.float)
writer.add_image("test2", img1_tensor / 255, 1, dataformats="HWC")

trans_totensor = transforms.ToTensor()
img1_tensor = trans_totensor(img1)
writer.add_image("test2", img1_tensor, 2)


# PIL.Image读入
img2 = Image.open(img_path)
img2 = np.array(img2)

img2_tensor = torch.tensor(img2, dtype=torch.float)
writer.add_image("test2", img2_tensor / 255, 3, dataformats="HWC")

trans_totensor = transforms.ToTensor()
img2_tensor = trans_totensor(img2)
writer.add_image("test2", img2_tensor, 4)


writer.close()

你可能感兴趣的:(深度学习,opencv)