python 使用transforms 将图片转为tensor数据类型

使用PIL读取图片

# 导入必要的模块
from PIL import Image
from torchvision import transforms
import numpy as np
from torch.utils.tensorboard import SummaryWriter

# 图片路径
img_path = 'test.img'
# PIL 读取图片
img = Image.open(img_path)
# 将PIL图片转为ndarray
img_arr = np.array(img)

# 新建一个ToTensor工厂
tensor_trans = transforms.ToTensor()
# 将图片转为tensor类型
tensor_img1 = tensor_trans(img)
# 将ndarray转为tensor类型
tensor_img2 = tensor_trans(img_arr)

# 将tensor写入tensorboard
# logs路径
log_dir = 'logs_tensor'
writer = SummaryWriter(log_dir)
# 添加图片
writer.add_image(tag='test',img_tensor=tensor_img1,global_step=1)
writer.add_image(tag='test',img_tensor=tensor_img2,global_step=2)
# 关闭writer
writer.close()

使用OpenCV读取图片

# 导入必要模块
import cv2
from torchvision import transforms
from torch.utils.tensorboard import SummaryWriter

# 图片路径
img_path = 'test.jpg'

# 使用OpenCV读取图片,图片路径不能包含中文
img = cv2.imread(img_path)
# 使用OpenCV读取图片的数据类型是ndarray
print(type(img))

# 新建一个ToTensor工厂
tensor_trans = transforms.ToTensor()
# 将img转为tensor类
tensor_img = tensor_trans(img)
print(type(tensor_img))

#logs路径
logs_dir = 'logs_tensor'
# 新建一个SummaryWriter
writer = SummaryWriter(logs_dir)
# 写入img
writer.add_image(tag='test',img_tensor=tensor_img,global_step=3)
# 关闭writer
writer.close()



 在控制台输入

tensorboard --logdir=logs_tensor --port=6608

可打开tensorboard查看所写入的图片

(端口默认为6006)

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