-
Notifications
You must be signed in to change notification settings - Fork 20
/
read_data.py
55 lines (46 loc) · 1.49 KB
/
read_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# encoding: utf-8
"""
Read images and corresponding labels.
"""
import torch
from torch.utils.data import Dataset
from PIL import Image
import os
class ChestXrayDataSet(Dataset):
def __init__(self, data_dir, image_list_file, transform=None):
"""
Args:
data_dir: path to image directory.
image_list_file: path to the file containing images
with corresponding labels.
transform: optional transform to be applied on a sample.
"""
image_names = []
labels = []
with open(image_list_file, "r") as f:
for line in f:
items = line.split()
image_name= items[0]
label = items[1:]
label = [int(i) for i in label]
image_name = os.path.join(data_dir, image_name)
image_names.append(image_name)
labels.append(label)
self.image_names = image_names
self.labels = labels
self.transform = transform
def __getitem__(self, index):
"""
Args:
index: the index of item
Returns:
image and its labels
"""
image_name = self.image_names[index]
image = Image.open(image_name).convert('RGB')
label = self.labels[index]
if self.transform is not None:
image = self.transform(image)
return image, torch.FloatTensor(label)
def __len__(self):
return len(self.image_names)