forked from CAMMA-public/cholect45
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader_pth.py
211 lines (190 loc) · 10.2 KB
/
dataloader_pth.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CODE RELEASE TO SUPPORT RESEARCH.
COMMERCIAL USE IS NOT PERMITTED.
#==============================================================================
An implementation based on:
***
C.I. Nwoye, T. Yu, C. Gonzalez, B. Seeliger, P. Mascagni, D. Mutter, J. Marescaux, N. Padoy.
Rendezvous: Attention Mechanisms for the Recognition of Surgical Action Triplets in Endoscopic Videos.
Medical Image Analysis, 78 (2022) 102433.
***
Created on Thu Oct 21 15:38:36 2021
#==============================================================================
Copyright 2021 The Research Group CAMMA Authors All Rights Reserved.
(c) Research Group CAMMA, University of Strasbourg, France
@ Laboratory: CAMMA - ICube
@ Author: Chinedu Innocent Nwoye
@ Website: http://camma.u-strasbg.fr
#==============================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#==============================================================================
"""
import os
import random
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
from torch.utils.data import Dataset, ConcatDataset, DataLoader
class CholecT50():
def __init__(self,
dataset_dir,
dataset_version="cholect45-cross-val",
test_fold=1,
augmentation_list=['original', 'vflip', 'hflip', 'contrast', 'rot90']):
""" Args
dataset_dir : common path to the dataset (excluding videos, output)
list_video : list video IDs, e.g: ['VID01', 'VID02']
aug : data augumentation style
split : data split ['train', 'val', 'test']
Call
batch_size: int,
shuffle: True or False
Return
tuple ((image), (tool_label, verb_label, target_label, triplet_label))
"""
self.dataset_dir = dataset_dir
self.list_dataset_version = {
"cholect45-cross-val": "45cv", # official data splits (cross-val)
"cholect50-cross-val": "50cv", # official data splits (cross-val)
"cholect50-challenge": "50ch", # data splits as used in CholecTriplet challenge
"cholect45": "45cv", # pointer to cholect45-cross-val
"cholect50": "50", # original data splits as used in rendezvous paper
}
dsv = self.list_dataset_version[dataset_version]
video_split = self.split_selector(case=dsv)
train_videos = sum([v for k,v in video_split.items() if k!=test_fold], []) if 'cv' in dsv else video_split['train']
test_videos = sum([v for k,v in video_split.items() if k==test_fold], []) if 'cv' in dsv else video_split['test']
if 'cv' in dsv:
train_videos = train_videos[:-5]
val_videos = train_videos[-5:]
else:
val_videos = video_split['val']
self.train_records = ['VID{}'.format(str(v).zfill(2)) for v in train_videos]
self.val_records = ['VID{}'.format(str(v).zfill(2)) for v in val_videos]
self.test_records = ['VID{}'.format(str(v).zfill(2)) for v in test_videos]
self.augmentations = {
'original': self.no_augumentation,
'vflip': transforms.RandomVerticalFlip(0.4),
'hflip': transforms.RandomHorizontalFlip(0.4),
'contrast': transforms.ColorJitter(brightness=0.1, contrast=0.2, saturation=0, hue=0),
'rot90': transforms.RandomRotation(90,expand=True),
'brightness': transforms.RandomAdjustSharpness(sharpness_factor=1.6, p=0.5),
'contrast': transforms.RandomAutocontrast(p=0.5),
}
self.augmentation_list = []
for aug in augmentation_list:
self.augmentation_list.append(self.augmentations[aug])
trainform, testform = self.transform()
self.build_train_dataset(trainform)
self.build_val_dataset(trainform)
self.build_test_dataset(testform)
def list_augmentations(self):
print(self.augmentations.keys())
def split_selector(self, case='50'):
switcher = {
'50': {
'train': [1, 15, 26, 40, 52, 65, 79, 2, 18, 27, 43, 56, 66, 92, 4, 22, 31, 47, 57, 68, 96, 5, 23, 35, 48, 60, 70, 103, 13, 25, 36, 49, 62, 75, 110],
'val' : [8, 12, 29, 50, 78],
'test' : [6, 51, 10, 73, 14, 74, 32, 80, 42, 111]
},
'50ch': {
'train': [1, 15, 26, 40, 52, 79, 2, 27, 43, 56, 66, 4, 22, 31, 47, 57, 68, 23, 35, 48, 60, 70, 13, 25, 49, 62, 75, 8, 12, 29, 50, 78, 6, 51, 10, 73, 14, 32, 80, 42],
'val': [5, 18, 36, 65, 74],
'test': [92, 96, 103, 110, 111]
},
'45cv': {
1: [79, 2, 51, 6, 25, 14, 66, 23, 50,],
2: [80, 32, 5, 15, 40, 47, 26, 48, 70,],
3: [31, 57, 36, 18, 52, 68, 10, 8, 73,],
4: [42, 29, 60, 27, 65, 75, 22, 49, 12,],
5: [78, 43, 62, 35, 74, 1, 56, 4, 13,],
},
'50cv': {
1: [79, 2, 51, 6, 25, 14, 66, 23, 50, 111],
2: [80, 32, 5, 15, 40, 47, 26, 48, 70, 96],
3: [31, 57, 36, 18, 52, 68, 10, 8, 73, 103],
4: [42, 29, 60, 27, 65, 75, 22, 49, 12, 110],
5: [78, 43, 62, 35, 74, 1, 56, 4, 13, 92],
},
}
return switcher.get(case)
def no_augumentation(self, x):
return x
def transform(self):
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
op_test = [transforms.Resize((256, 448)), transforms.Resize((256, 448)), transforms.ToTensor(), normalize,]
op_train = [transforms.Resize((256, 448))] + self.augmentation_list + [transforms.Resize((256, 448)), transforms.ToTensor(), normalize,]
testform = transforms.Compose(op_test)
trainform = transforms.Compose(op_train)
return trainform, testform
def build_train_dataset(self, transform):
iterable_dataset = []
for video in self.train_records:
dataset = T50(img_dir = os.path.join(self.dataset_dir, 'data', video),
triplet_file = os.path.join(self.dataset_dir, 'triplet', '{}.txt'.format(video)),
tool_file = os.path.join(self.dataset_dir, 'instrument', '{}.txt'.format(video)),
verb_file = os.path.join(self.dataset_dir, 'verb', '{}.txt'.format(video)),
target_file = os.path.join(self.dataset_dir, 'target', '{}.txt'.format(video)),
transform=transform)
iterable_dataset.append(dataset)
self.train_dataset = ConcatDataset(iterable_dataset)
def build_val_dataset(self, transform):
iterable_dataset = []
for video in self.val_records:
dataset = T50(img_dir = os.path.join(self.dataset_dir, 'data', video),
triplet_file = os.path.join(self.dataset_dir, 'triplet', '{}.txt'.format(video)),
tool_file = os.path.join(self.dataset_dir, 'instrument', '{}.txt'.format(video)),
verb_file = os.path.join(self.dataset_dir, 'verb', '{}.txt'.format(video)),
target_file = os.path.join(self.dataset_dir, 'target', '{}.txt'.format(video)),
transform=transform)
iterable_dataset.append(dataset)
self.val_dataset = ConcatDataset(iterable_dataset)
def build_test_dataset(self, transform):
iterable_dataset = []
for video in self.test_records:
dataset = T50(img_dir = os.path.join(self.dataset_dir, 'data', video),
triplet_file = os.path.join(self.dataset_dir, 'triplet', '{}.txt'.format(video)),
tool_file = os.path.join(self.dataset_dir, 'instrument', '{}.txt'.format(video)),
verb_file = os.path.join(self.dataset_dir, 'verb', '{}.txt'.format(video)),
target_file = os.path.join(self.dataset_dir, 'target', '{}.txt'.format(video)),
transform=transform)
iterable_dataset.append(dataset)
self.test_dataset = iterable_dataset
def build(self):
return (self.train_dataset, self.val_dataset, self.test_dataset)
class T50(Dataset):
def __init__(self, img_dir, triplet_file, tool_file, verb_file, target_file, transform=None, target_transform=None):
self.triplet_labels = np.loadtxt(triplet_file, dtype=np.int, delimiter=',',)
self.tool_labels = np.loadtxt(tool_file, dtype=np.int, delimiter=',',)
self.verb_labels = np.loadtxt(verb_file, dtype=np.int, delimiter=',',)
self.target_labels = np.loadtxt(target_file, dtype=np.int, delimiter=',',)
self.img_dir = img_dir
self.transform = transform
self.target_transform = target_transform
def __len__(self):
return len(self.triplet_labels)
def __getitem__(self, index):
triplet_label = self.triplet_labels[index, 1:]
tool_label = self.tool_labels[index, 1:]
verb_label = self.verb_labels[index, 1:]
target_label = self.target_labels[index, 1:]
basename = "{}.png".format(str(self.triplet_labels[index, 0]).zfill(6))
img_path = os.path.join(self.img_dir, basename)
image = Image.open(img_path)
if self.transform:
image = self.transform(image)
if self.target_transform:
triplet_label = self.target_transform(triplet_label)
return image, (tool_label, verb_label, target_label, triplet_label)
if __name__ == "__main__":
print("Refers to https://github.com/CAMMA-public/cholect45 for the usage guide.")