forked from ternaus/robot-surgery-segmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
56 lines (44 loc) · 1.79 KB
/
dataset.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
55
56
import torch
import numpy as np
import cv2
from torch.utils.data import Dataset
import prepare_data
from albumentations.torch.functional import img_to_tensor
class RoboticsDataset(Dataset):
def __init__(self, file_names, to_augment=False, transform=None, mode='train', problem_type=None):
self.file_names = file_names
self.to_augment = to_augment
self.transform = transform
self.mode = mode
self.problem_type = problem_type
def __len__(self):
return len(self.file_names)
def __getitem__(self, idx):
img_file_name = self.file_names[idx]
image = load_image(img_file_name)
mask = load_mask(img_file_name, self.problem_type)
data = {"image": image, "mask": mask}
augmented = self.transform(**data)
image, mask = augmented["image"], augmented["mask"]
if self.mode == 'train':
if self.problem_type == 'binary':
return img_to_tensor(image), torch.from_numpy(np.expand_dims(mask, 0)).float()
else:
return img_to_tensor(image), torch.from_numpy(mask).long()
else:
return img_to_tensor(image), str(img_file_name)
def load_image(path):
img = cv2.imread(str(path))
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def load_mask(path, problem_type):
if problem_type == 'binary':
mask_folder = 'binary_masks'
factor = prepare_data.binary_factor
elif problem_type == 'parts':
mask_folder = 'parts_masks'
factor = prepare_data.parts_factor
elif problem_type == 'instruments':
factor = prepare_data.instrument_factor
mask_folder = 'instruments_masks'
mask = cv2.imread(str(path).replace('images', mask_folder).replace('jpg', 'png'), 0)
return (mask / factor).astype(np.uint8)