计算机视觉实践(街景字符编码识别)(二)

计算机视觉实践(街景字符编码识别)(二)

2.数据读取与数据增扩

Pytorch的数据读取机制

DataSet

from torch.utils.data.dataset import Dataset
class SVHNDataset(Dataset):
    def __init__(self, img_path, img_label, transform=None):
        self.img_path = img_path
        self.img_label = img_label 
        if transform is not None:
            self.transform = transform
        else:
            self.transform = None

    def __getitem__(self, index):
        img = Image.open(self.img_path[index]).convert('RGB')

        if self.transform is not None:
            img = self.transform(img)
        
        lbl = np.array(self.img_label[index], dtype=np.int)
        lbl = list(lbl)  + (5 - len(lbl)) * [10]
        return img, torch.from_numpy(np.array(lbl[:5]))
        //getitem 接受一个索引,返回一个样本

    def __len__(self):
        return len(self.img_path)

DataLoader

train_loader = torch.utils.data.DataLoader(
    SVHNDataset(train_path, train_label,
                transforms.Compose([
                    transforms.Resize((64, 128)),
                    transforms.RandomCrop((60, 120)),
                    transforms.ColorJitter(0.3, 0.3, 0.2),
                    transforms.RandomRotation(10),
                    transforms.ToTensor(),
                    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])), 
    batch_size=40,  //批大小
    shuffle=True, //是否乱序
    num_workers=10, //是否多进程读取数据
)

读取数据

train_path = glob.glob('../input/train/*.png')
train_path.sort()
train_json = json.load(open('../input/train.json'))
train_label = [train_json[x]['label'] for x in train_json]
print(len(train_path), len(train_label))

数据增强

import torchvision.transforms as transforms
//Crop
transforms.RandomCrop(size,
                      padding = None,
                      pad_if_needed = False,
                      fill =0,
                      padding_mode='constant')
//Rotation
RandomRotation(degrees,
               resample= Flase,
               expand = Flase,
               center = None)
//Flip
RandomHorizontalFlip()
RandonVerticalFlip()
//Pad
transform.Pad()
//color
transform.ColorJitter()
Grayscale()
RandomGrayscale()
//仿射变换
RandomAffine() 

你可能感兴趣的:(计算机视觉实践(街景字符编码识别)(二))