|
3 | 3 |
|
4 | 4 | import logging |
5 | 5 | import os |
| 6 | +import h5py |
6 | 7 | import pandas as pd |
7 | 8 | import numpy as np |
8 | 9 | from torch.utils.data import Dataset |
9 | 10 | from pymic import TaskType |
10 | 11 | from pymic.io.image_read_write import load_image_as_nd_array |
11 | 12 |
|
| 13 | +def check_and_expand_dim(x, img_dim): |
| 14 | + """ |
| 15 | + check the input dim and expand it with a channel dimension if necessary. |
| 16 | + For 2D images, return a 3D numpy array with a shape of [C, H, W] |
| 17 | + for 3D images, return a 3D numpy array with a shape of [C, D, H, W] |
| 18 | + """ |
| 19 | + input_dim = len(x.shape) |
| 20 | + if(input_dim == 2 and img_dim == 2): |
| 21 | + x = np.expand_dims(x, axis = 0) |
| 22 | + elif(input_dim == 3 and img_dim == 3): |
| 23 | + x = np.expand_dims(x, axis = 0) |
| 24 | + return x |
| 25 | + |
12 | 26 | class NiftyDataset(Dataset): |
13 | 27 | """ |
14 | 28 | Dataset for loading images for segmentation. It generates 4D tensors with |
15 | 29 | dimention order [C, D, H, W] for 3D images, and 3D tensors |
16 | 30 | with dimention order [C, H, W] for 2D images. |
17 | 31 |
|
18 | 32 | :param root_dir: (str) Directory with all the images. |
19 | | - :param csv_file: (str) Path to the csv file with image names. |
20 | | - :param modal_num: (int) Number of modalities. |
| 33 | + :param csv: (str) Path to the csv file with image names. If it is None, |
| 34 | + the images will be those under root_dir. This only works for testing with |
| 35 | + a single input modality. If the images are stored in h5 files, the *.csv file |
| 36 | + only has one column, while for other types of images such as .nii.gz and.png, |
| 37 | + each column is for an input modality, and the last column is for label. |
| 38 | + :param modal_num: (int) Number of modalities. This is only used if the data_file is *.csv. |
| 39 | + :param image_dim: (int) Spacial dimension of the input image. This is ony used for h5 files. |
21 | 40 | :param with_label: (bool) Load the data with segmentation ground truth or not. |
22 | 41 | :param transform: (list) List of transforms to be applied on a sample. |
23 | 42 | The built-in transforms can listed in :mod:`pymic.transform.trans_dict`. |
24 | 43 | """ |
25 | | - # def __init__(self, root_dir, csv_file, modal_num = 1, |
26 | | - def __init__(self, root_dir, csv_file, modal_num = 1, allow_missing_modal = False, |
27 | | - with_label = False, transform=None, task = TaskType.SEGMENTATION): |
| 44 | + def __init__(self, root_dir, csv_file, modal_num = 1, image_dim = 3, allow_missing_modal = False, |
| 45 | + with_label = True, transform=None, task = TaskType.SEGMENTATION): |
28 | 46 | self.root_dir = root_dir |
29 | | - self.csv_items = pd.read_csv(csv_file) |
| 47 | + if(csv_file is not None): |
| 48 | + self.csv_items = pd.read_csv(csv_file) |
| 49 | + else: |
| 50 | + img_names = os.listdir(root_dir) |
| 51 | + img_names = [item for item in img_names if ("nii" in item or "jpg" in item or |
| 52 | + "jpeg" in item or "bmp" in item or "png" in item)] |
| 53 | + csv_dict = {"image":img_names} |
| 54 | + self.csv_items = pd.DataFrame.from_dict(csv_dict) |
| 55 | + |
30 | 56 | self.modal_num = modal_num |
| 57 | + self.image_dim = image_dim |
31 | 58 | self.allow_emtpy= allow_missing_modal |
32 | 59 | self.with_label = with_label |
33 | 60 | self.transform = transform |
34 | 61 | self.task = task |
| 62 | + self.h5files = False |
35 | 63 | assert self.task in [TaskType.SEGMENTATION, TaskType.RECONSTRUCTION] |
36 | 64 |
|
37 | | - csv_keys = list(self.csv_items.keys()) |
38 | | - if('label' not in csv_keys): |
| 65 | + # check if the files are h5 images, and if the labels are provided. |
| 66 | + temp_name = self.csv_items.iloc[0, 0] |
| 67 | + logging.warning(temp_name) |
| 68 | + if(temp_name.endswith(".h5")): |
| 69 | + self.h5files = True |
| 70 | + temp_full_name = "{0:}/{1:}".format(self.root_dir, temp_name) |
| 71 | + h5f = h5py.File(temp_full_name, 'r') |
| 72 | + if('label' not in h5f): |
| 73 | + self.with_label = False |
| 74 | + else: |
| 75 | + csv_keys = list(self.csv_items.keys()) |
| 76 | + if('label' not in csv_keys): |
| 77 | + self.with_label = False |
| 78 | + |
| 79 | + self.image_weight_idx = None |
| 80 | + self.pixel_weight_idx = None |
| 81 | + if('image_weight' in csv_keys): |
| 82 | + self.image_weight_idx = csv_keys.index('image_weight') |
| 83 | + if('pixel_weight' in csv_keys): |
| 84 | + self.pixel_weight_idx = csv_keys.index('pixel_weight') |
| 85 | + if(not self.with_label): |
39 | 86 | logging.warning("`label` section is not found in the csv file {0:}".format( |
40 | | - csv_file) + "\n -- This is only allowed for self-supervised learning" + |
| 87 | + csv_file) + "or the corresponding h5 file." + |
| 88 | + "\n -- This is only allowed for self-supervised learning" + |
41 | 89 | "\n -- when `SelfSuperviseLabel` is used in the transform, or when" + |
42 | 90 | "\n -- loading the unlabeled data for preprocessing.") |
43 | | - self.with_label = False |
44 | | - self.image_weight_idx = None |
45 | | - self.pixel_weight_idx = None |
46 | | - if('image_weight' in csv_keys): |
47 | | - self.image_weight_idx = csv_keys.index('image_weight') |
48 | | - if('pixel_weight' in csv_keys): |
49 | | - self.pixel_weight_idx = csv_keys.index('pixel_weight') |
50 | 91 |
|
51 | 92 | def __len__(self): |
52 | 93 | return len(self.csv_items) |
@@ -92,36 +133,46 @@ def __get_pixel_weight__(self, idx): |
92 | 133 | def __getitem__(self, idx): |
93 | 134 | names_list, image_list = [], [] |
94 | 135 | image_shape = None |
95 | | - for i in range (self.modal_num): |
96 | | - image_name = self.csv_items.iloc[idx, i] |
97 | | - image_full_name = "{0:}/{1:}".format(self.root_dir, image_name) |
98 | | - if(os.path.exists(image_full_name)): |
99 | | - image_dict = load_image_as_nd_array(image_full_name) |
100 | | - image_data = image_dict['data_array'] |
101 | | - elif(self.allow_emtpy and image_shape is not None): |
102 | | - image_data = np.zeros(image_shape) |
103 | | - else: |
104 | | - raise KeyError("File not found: {0:}".format(image_full_name)) |
105 | | - if(i == 0): |
106 | | - image_shape = image_data.shape |
107 | | - names_list.append(image_name) |
108 | | - image_list.append(image_data) |
109 | | - image = np.concatenate(image_list, axis = 0) |
110 | | - image = np.asarray(image, np.float32) |
111 | | - |
112 | | - sample = {'image': image, 'names' : names_list, |
113 | | - 'origin':image_dict['origin'], |
114 | | - 'spacing': image_dict['spacing'], |
115 | | - 'direction':image_dict['direction']} |
116 | | - if (self.with_label): |
117 | | - sample['label'], label_name = self.__getlabel__(idx) |
118 | | - sample['names'].append(label_name) |
119 | | - assert(image.shape[1:] == sample['label'].shape[1:]) |
120 | | - if (self.image_weight_idx is not None): |
121 | | - sample['image_weight'] = self.csv_items.iloc[idx, self.image_weight_idx] |
122 | | - if (self.pixel_weight_idx is not None): |
123 | | - sample['pixel_weight'] = self.__get_pixel_weight__(idx) |
124 | | - assert(image.shape[1:] == sample['pixel_weight'].shape[1:]) |
| 136 | + if(self.h5files): |
| 137 | + sample_name = self.csv_items.iloc[idx, 0] |
| 138 | + h5f = h5py.File(self.root_dir + '/' + sample_name, 'r') |
| 139 | + img = check_and_expand_dim(h5f['image'][:], self.image_dim) |
| 140 | + sample = {'image':img} |
| 141 | + if(self.with_label): |
| 142 | + lab = check_and_expand_dim(h5f['label'][:], self.image_dim) |
| 143 | + sample['label'] = lab |
| 144 | + sample['names'] = [sample_name] |
| 145 | + else: |
| 146 | + for i in range (self.modal_num): |
| 147 | + image_name = self.csv_items.iloc[idx, i] |
| 148 | + image_full_name = "{0:}/{1:}".format(self.root_dir, image_name) |
| 149 | + if(os.path.exists(image_full_name)): |
| 150 | + image_dict = load_image_as_nd_array(image_full_name) |
| 151 | + image_data = image_dict['data_array'] |
| 152 | + elif(self.allow_emtpy and image_shape is not None): |
| 153 | + image_data = np.zeros(image_shape) |
| 154 | + else: |
| 155 | + raise KeyError("File not found: {0:}".format(image_full_name)) |
| 156 | + if(i == 0): |
| 157 | + image_shape = image_data.shape |
| 158 | + names_list.append(image_name) |
| 159 | + image_list.append(image_data) |
| 160 | + image = np.concatenate(image_list, axis = 0) |
| 161 | + image = np.asarray(image, np.float32) |
| 162 | + |
| 163 | + sample = {'image': image, 'names' : names_list, |
| 164 | + 'origin':image_dict['origin'], |
| 165 | + 'spacing': image_dict['spacing'], |
| 166 | + 'direction':image_dict['direction']} |
| 167 | + if (self.with_label): |
| 168 | + sample['label'], label_name = self.__getlabel__(idx) |
| 169 | + sample['names'].append(label_name) |
| 170 | + assert(image.shape[1:] == sample['label'].shape[1:]) |
| 171 | + if (self.image_weight_idx is not None): |
| 172 | + sample['image_weight'] = self.csv_items.iloc[idx, self.image_weight_idx] |
| 173 | + if (self.pixel_weight_idx is not None): |
| 174 | + sample['pixel_weight'] = self.__get_pixel_weight__(idx) |
| 175 | + assert(image.shape[1:] == sample['pixel_weight'].shape[1:]) |
125 | 176 | if self.transform: |
126 | 177 | sample = self.transform(sample) |
127 | 178 |
|
|
0 commit comments