import numpy
import os
from torch.utils.data import Dataset
from PIL import Image
class Mydata(Dataset):
def __init__(self,root_dir,label_dir):
self.root_dir = root_dir
self.label_dir= label_dir
self . path = os.path.join(self.root_dir, self.label_dir)
self.img_path = os.listdir(self.path)
def __getitem__(self, index):
img_name = self.img_path[index]
img_item_path = os.path.join(self.root_dir,self.label_dir,img_name)
img = Image.open(img_item_path)
label = self.label_dir
return img, label
def __len__(self):
return len(self.img_path)
在上述的代码之中,是把整个文件夹中的所有关于ant的图片作为一个整体,(类似于数组),
然后就可以用类似于数列的取地址的方式来进行访问了。
差不多就是自己定义了一个数据的类型,(参考struct),通过数组式的访问有图像PIL和label的tuple类型返回值
通过这一种方式来在tensorboard之中打开Image
Shape:
img_tensor:Defaultis:math:`(3,H,W)`.Youcanuse``torchvision.utils.make_grid()``to
convertabatchoftensorinto3xHxWformatorcall``add_images``andletusdothejob.
Tensorwith:math:`(1,H,W)`,:math:`(H,W)`,:math:`(H,W,3)`isalsosuitableaslongas
corresponding``dataformats``argumentispassed,e.g.``CHW``,``HWC``,``HW``.
transforms.py工具箱
输入:一些特定格式的图片
--> totensor #转化为 tensor 文件
--> resize
从而实现预期的一些变化
tensor数据类型
'''
img(PIL format)
>>> via method...transforms.Resize(512,512) or transforms.Resize(512) # resize proportionately
...Methods Objectified from Class Resize, the function, too, can be a kind of object able to be objectified
--> img_resized(PIL format)
... via method...transforms.ToTensor()
...Objectified from Class: ToTensor.
>>> tensor_transform = transforms.ToTensor()
>>> img_tensor = tensor_transform(img_PIL)
--> img_tensor(Tensor format)
... via Tensorboard to print the image
'''
'''
use class Compose to shorten the procedure like bellow:
img(PIL format)
... activate an instance of transforms.Compose Class
compose can sum up a series of transforms objects together and operate them orderly.
>>> trans_compose = transforms.Compose([transforms.Resize(512),transforms.ToTensor()])
>>> img_tensor_resize = trans_compose(img)
--> output: resized image in Tensor Format
'''
'''
note::
One significant thing: we've learnt in OOP(Object Oriented Programming) that we can objectify a class
and created a precise instance related to the class.
In this code, we can find out that objects can sometimes be the abstractions of a certain function. The
function is first created and later called.
'''
from torchvision import transforms
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
img_path = r"dataset/val/bees/2506114833_90a41c5267.jpg"
img_PIL = Image.open(img_path)
tensor_transform = transforms.ToTensor()
# Objectify the tools in the module transform
img_tensor = tensor_transform(img_PIL)
print(img_tensor)
writer = SummaryWriter("logs")
writer.add_image("bees", img_tensor)
trans_normalize = transforms.Normalize([0.5, 0.5, 0.7], [2, 2, 2])
img_norm = trans_normalize(img_tensor)
writer.add_image("new normalized", img_norm)
writer.close()