|
| 1 | +import os |
| 2 | +import pandas as pd |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +import torch |
| 6 | +import torch.utils.data as data |
| 7 | + |
| 8 | +from torchsample.transforms import RandomRotate, RandomTranslate, RandomFlip, ToTensor, Compose, RandomAffine |
| 9 | +from torchvision import transforms |
| 10 | + |
| 11 | +INPUT_DIM = 224 |
| 12 | +MAX_PIXEL_VAL = 255 |
| 13 | +MEAN = 58.09 |
| 14 | +STDDEV = 49.73 |
| 15 | + |
| 16 | +class MRData(): |
| 17 | + """This class used to load MRnet dataset from `./images` dir |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self,task = 'acl', train = True, transform = None, weights = None): |
| 21 | + """Initialize the dataset |
| 22 | +
|
| 23 | + Args: |
| 24 | + plane : along which plane to load the data |
| 25 | + task : for which task to load the labels |
| 26 | + train : whether to load the train or val data |
| 27 | + transform : which transforms to apply |
| 28 | + weights (Tensor) : Give wieghted loss to postive class eg. `weights=torch.tensor([2.223])` |
| 29 | + """ |
| 30 | + self.planes=['axial', 'coronal', 'sagittal'] |
| 31 | + self.records = None |
| 32 | + # an empty dictionary |
| 33 | + self.image_path={} |
| 34 | + |
| 35 | + if train: |
| 36 | + self.records = pd.read_csv('./images/train-{}.csv'.format(task),header=None, names=['id', 'label']) |
| 37 | + |
| 38 | + ''' |
| 39 | + self.image_path[<plane>]= dictionary {<plane>: path to folder containing |
| 40 | + image for that plane} |
| 41 | + ''' |
| 42 | + for plane in self.planes: |
| 43 | + self.image_path[plane] = './images/train/{}/'.format(plane) |
| 44 | + else: |
| 45 | + transform = None |
| 46 | + self.records = pd.read_csv('./images/valid-{}.csv'.format(task),header=None, names=['id', 'label']) |
| 47 | + ''' |
| 48 | + self.image_path[<plane>]= dictionary {<plane>: path to folder containing |
| 49 | + image for that plane} |
| 50 | + ''' |
| 51 | + for plane in self.planes: |
| 52 | + self.image_path[plane] = './images/valid/{}/'.format(plane) |
| 53 | + |
| 54 | + |
| 55 | + self.transform = transform |
| 56 | + |
| 57 | + self.records['id'] = self.records['id'].map( |
| 58 | + lambda i: '0' * (4 - len(str(i))) + str(i)) |
| 59 | + # empty dictionary |
| 60 | + self.paths={} |
| 61 | + for plane in self.planes: |
| 62 | + self.paths[plane] = [self.image_path[plane] + filename + |
| 63 | + '.npy' for filename in self.records['id'].tolist()] |
| 64 | + |
| 65 | + self.labels = self.records['label'].tolist() |
| 66 | + |
| 67 | + pos = sum(self.labels) |
| 68 | + neg = len(self.labels) - pos |
| 69 | + |
| 70 | + # Find the wieghts of pos and neg classes |
| 71 | + if weights: |
| 72 | + self.weights = torch.FloatTensor(weights) |
| 73 | + else: |
| 74 | + self.weights = torch.FloatTensor([neg / pos]) |
| 75 | + |
| 76 | + print('Number of -ve samples : ', neg) |
| 77 | + print('Number of +ve samples : ', pos) |
| 78 | + print('Weights for loss is : ', self.weights) |
| 79 | + |
| 80 | + def __len__(self): |
| 81 | + """Return the total number of images in the dataset.""" |
| 82 | + return len(self.records) |
| 83 | + |
| 84 | + def __getitem__(self, index): |
| 85 | + """ |
| 86 | + Returns `(images,labels)` pair |
| 87 | + where image is a list [imgsPlane1,imgsPlane2,imgsPlane3] |
| 88 | + and labels is a list [gt,gt,gt] |
| 89 | + """ |
| 90 | + img_raw = {} |
| 91 | + |
| 92 | + for plane in self.planes: |
| 93 | + img_raw[plane] = np.load(self.paths[plane][index]) |
| 94 | + img_raw[plane] = self._resize_image(img_raw[plane]) |
| 95 | + |
| 96 | + label = self.labels[index] |
| 97 | + if label == 1: |
| 98 | + label = torch.FloatTensor([1]) |
| 99 | + elif label == 0: |
| 100 | + label = torch.FloatTensor([0]) |
| 101 | + |
| 102 | + return [img_raw[plane] for plane in self.planes], label |
| 103 | + |
| 104 | + def _resize_image(self, image): |
| 105 | + """Resize the image to `(3,224,224)` and apply |
| 106 | + transforms if possible. |
| 107 | + """ |
| 108 | + # Resize the image |
| 109 | + pad = int((image.shape[2] - INPUT_DIM)/2) |
| 110 | + image = image[:,pad:-pad,pad:-pad] |
| 111 | + image = (image-np.min(image))/(np.max(image)-np.min(image))*MAX_PIXEL_VAL |
| 112 | + image = (image - MEAN) / STDDEV |
| 113 | + |
| 114 | + if self.transform: |
| 115 | + image = self.transform(image) |
| 116 | + else: |
| 117 | + image = np.stack((image,)*3, axis=1) |
| 118 | + |
| 119 | + image = torch.FloatTensor(image) |
| 120 | + return image |
| 121 | + |
| 122 | +def load_data(task : str): |
| 123 | + |
| 124 | + # Define the Augmentation here only |
| 125 | + augments = Compose([ |
| 126 | + transforms.Lambda(lambda x: torch.Tensor(x)), |
| 127 | + RandomRotate(25), |
| 128 | + RandomTranslate([0.11, 0.11]), |
| 129 | + RandomFlip(), |
| 130 | + transforms.Lambda(lambda x: x.repeat(3, 1, 1, 1).permute(1, 0, 2, 3)), |
| 131 | + ]) |
| 132 | + |
| 133 | + print('Loading Train Dataset of {} task...'.format(task)) |
| 134 | + train_data = MRData(task, train=True, transform=augments) |
| 135 | + train_loader = data.DataLoader( |
| 136 | + train_data, batch_size=1, num_workers=11, shuffle=True |
| 137 | + ) |
| 138 | + |
| 139 | + print('Loading Validation Dataset of {} task...'.format(task)) |
| 140 | + val_data = MRData(task, train=False) |
| 141 | + val_loader = data.DataLoader( |
| 142 | + val_data, batch_size=1, num_workers=11, shuffle=False |
| 143 | + ) |
| 144 | + |
| 145 | + return train_loader, val_loader, train_data.weights, val_data.weights |
0 commit comments