Tensorboard中的SummaryWriter使用
- 导入数据包
from torch.utils.tensorboard import SummaryWriter
- 构造函数方法
writer = SummaryWriter("logs")
- add_scalar
'''
tag:数据标题
global_step:x轴数据
scalar_value:y轴数据
'''
for i in range(100):
writer.add_scalar("y=x",i,i)
- 如何打开文件
- 打开terminal控制台
- 输入tensorboard --logdir=(事件文件所在文件夹名) (可选)–port=6007等
- 点击所出现的地址
- add_image
'''
tag:数据标题,
img_tensor:是ndarray类型,是有数据要求的,一般默认为(3,H,W),如果要修改,则需要在最后加上dataformats设置,e.g. ``CHW``, ``HWC``, ``HW``,可以使用shape来查看是什么形状
'''
image_path = "study_dataset/train/ants_image/0013035.jpg"
image_PIL = Image.open(image_path)
image_array = np.array(image_PIL)
writer.add_image("test",image_array,1,dataformats='HWC')
torchvision的transforms使用(图片格式转换)
如何使用
- 导入数据包
from torchvision import transforms
- 使用:这里注意我第一次使用时出现报错->numpy版本高于2.0
pip install numpy<2
img_path = "study_dataset/train/ants_image/0013035.jpg"
img = Image.open(img_path)
tensor_trans = transforms.ToTensor()
img_tensor = tensor_trans(img)
print(type(img_tensor))
常见的Transforms
package名 |
使用方法 |
输入类型 |
输出类型 |
PIL->Image |
Image.open() |
String |
PIL |
cv2 |
cv.imread() |
String |
ndarrays |
torchvision->transforms |
ToTensor() |
PIL/ndarray |
tensor |
torchvision->transforms |
ToPILImage() |
tensor/ndarray |
PIL |
torchvision->transforms |
Normalize() |
tensor |
tensor |
torchvision->transforms |
Resize() |
PIL |
PIL |
torchvision->transforms |
Compose() |
expect:tensor |
未定 |
torchvision->transforms |
RandomCrop() |
expect:tensor |
tensor |
- API
Normalize(mean,std,inplace=False)
- 代码示例
img_path = "study_dataset/train/ants_image/0013035.jpg"
img = Image.open(img_path)
trans_tenstor = transforms.ToTensor()
img_tensor = trans_tenstor(img)
tensor_trans = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
img_norm = tensor_trans(img_tensor)
- API
Resize(pic_size,interpolation=InterpolationMode.BILINEAR, max_size=None, antialias=True)
- 代码示例
img_path = "study_dataset/train/ants_image/0013035.jpg"
img = Image.open(img_path)
trans_resize = transforms.Resize((512,512))
img_resize = trans_resize(img)
Compose([transform,transform,...])
- 代码示例
trans_resize_2 = transforms.Resize(512)
trans_compose = transforms.Compose([trans_resize_2,trans_tenstor])
img_compose = trans_compose(img)
RandomCrop(size, padding=None, pad_if_needed=False, fill=0, padding_mode="constant")
- 代码示例
trans_RC = transforms.RandomCrop(512)
trans_compose_2 = transforms.Compose([trans_RC,trans_tenstor])
img_RC = trans_compose_2(img)