-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_noise_idn.py
200 lines (182 loc) · 7.44 KB
/
generate_noise_idn.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
from locale import LC_NUMERIC
import os
from collections import defaultdict
import numpy as np
from PIL import Image
import shutil
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as ET
def _has_only_empty_bbox(anno):
return all(any(o <= 1 for o in obj["bbox"][2:]) for obj in anno)
class VOCDataset:
CLASSES = (
"__background__ ",
# "dyed-lifted-polyp",
# "dyed-resection-margin",
# "polyp",
"adenomatous",
"hyperplastic",
)
def __init__(self, root, split='trainval', base_dir='.', keep_difficult=True, img_ext='.jpg', dataset_name=''):
self.root = root
self.split = split
self.keep_difficult = keep_difficult
self.img_ext = img_ext
# voc_root = os.path.join(self.root, base_dir)
voc_root = self.root
images_dir = os.path.join(voc_root, 'JPEGImages')
self.annotation_dir = os.path.join(voc_root, 'Annotations')
# super().__init__(images_dir, dataset_name)
splits_dir = os.path.join(voc_root, 'ImageSets/Main')
split_f = os.path.join(splits_dir, split + '.txt')
with open(os.path.join(split_f), "r") as f:
ids = [x.strip() for x in f.readlines()]
self.ids = ids
cat_ids = list(range(len(VOCDataset.CLASSES)))
self.label2cat = {
label: cat for label, cat in enumerate(cat_ids)
}
def get_annotations_by_image_id(self, img_id):
ann_path = os.path.join(self.annotation_dir, img_id + '.xml')
# print(ann_path)
target = self.parse_voc_xml(ET.parse(ann_path).getroot())['annotation']
img_info = {
'width': target['size']['width'],
'height': target['size']['height'],
'id': img_id,
'file_name': img_id + self.img_ext,
}
boxes = []
labels = []
difficult = []
if 'object' not in target:
print(ann_path)
for obj in target['object']:
is_difficult = bool(int(obj['difficult']))
if is_difficult and not self.keep_difficult:
continue
label_name = obj['name']
if label_name not in self.CLASSES:
continue
difficult.append(is_difficult)
label_id = self.CLASSES.index(label_name)
box = obj['bndbox']
box = list(map(lambda x: float(x) - 1, [box['xmin'], box['ymin'], box['xmax'], box['ymax']]))
boxes.append(box)
labels.append(label_id)
boxes = np.array(boxes).reshape((-1, 4))
labels = np.array(labels)
difficult = np.array(difficult)
return {'img_info': img_info, 'boxes': boxes, 'labels': labels, 'difficult': difficult}
def parse_voc_xml(self, node):
voc_dict = {}
children = list(node)
if children:
def_dic = defaultdict(list)
for dc in map(self.parse_voc_xml, children):
for ind, v in dc.items():
def_dic[ind].append(v)
voc_dict = {
node.tag: {k: v if k == 'object' else v[0] for k, v in def_dic.items()}
}
elif node.text:
text = node.text.strip()
voc_dict[node.tag] = text
return voc_dict
def count_instances(img_level_annos, total_instances): # Add all instances to a list
for instance_index_in_img in range(img_level_annos['labels'].shape[0]):
instance = {}
instance["file_name"] = img_level_annos['img_info']['file_name'][:-3] + 'xml' # change .jpg to .xml
instance["boxes"] = img_level_annos["boxes"][instance_index_in_img]
instance["labels"] = img_level_annos["labels"][instance_index_in_img]
# print(instance)
total_instances.append(instance)
import random
from copy import deepcopy
seed = 1997
random.seed(seed)
def generate_sym_noise(VOC_dir, split, th):
total_instances = []
voc2007 = VOCDataset(VOC_dir, split=split)
classes_idxs = list(np.arange(len(voc2007.CLASSES)))
# DEFAULTS
noise_instances = []
with open("/home/xliu423/content/federated/cl_0.txt", "r") as f:
lpre = len(noise_instances)
for line in f.readlines():
line = line.strip('\n').split("\t")
if float(line[1]) < th:
noise_instances.append(line[0]+".xml")
lcur = len(noise_instances)
print(lcur - lpre)
with open("/home/xliu423/content/federated/cl_1.txt", "r") as f:
lpre = len(noise_instances)
for line in f.readlines():
line = line.strip('\n').split("\t")
if float(line[1]) < th:
noise_instances.append(line[0]+".xml")
lcur = len(noise_instances)
print(lcur - lpre)
with open("/home/xliu423/content/federated/cl_2.txt", "r") as f:
lpre = len(noise_instances)
for line in f.readlines():
line = line.strip('\n').split("\t")
if float(line[1]) < th:
noise_instances.append(line[0]+".xml")
lcur = len(noise_instances)
print(lcur - lpre)
with open("/home/xliu423/content/federated/cl_3.txt", "r") as f:
lpre = len(noise_instances)
for line in f.readlines():
line = line.strip('\n').split("\t")
if float(line[1]) < th:
noise_instances.append(line[0]+".xml")
lcur = len(noise_instances)
print(lcur - lpre)
# get original anno files
anno_dir = os.path.join(VOC_dir, 'Annotations')
anno_list = os.listdir(anno_dir)
# make noise dir
noisy_anno_dir = os.path.join(VOC_dir, 'Noisy_Annotations_seed_{}_idn'.format(seed))
print('making noisy dir {}'.format(noisy_anno_dir))
if not os.path.exists(noisy_anno_dir):
os.mkdir(noisy_anno_dir)
# one-by-one copy
for clean_anno in anno_list:
shutil.copy(os.path.join(anno_dir, clean_anno), os.path.join(noisy_anno_dir, clean_anno))
# change the idx in obj
for instance in noise_instances:
tree = ET.parse(os.path.join(noisy_anno_dir, instance))
root = tree.getroot()
############################
# Put "noise" into XML
# noise = Element('noise')
# noise.text="True"
# root.append(noise)
############################
for obj in root.findall('object'):
box = obj.findall("bndbox")[0]
xmin = float(box[0].text) - 1
ymin = float(box[1].text) - 1
xmax = float(box[2].text) - 1
ymax = float(box[3].text) - 1
box = np.array([xmin, ymin, xmax, ymax])
# if (box == instance["boxes"]).all(): # This obj is the instance that we want to make it noisy
classes_idxs_new = deepcopy(list(classes_idxs))
name = obj.findall("name")[0]
if name == "adenomatous":
classes_idxs_new.remove(1)
elif name == "hyperplastic":
classes_idxs_new.remove(2)
# DO WE WANT TRANSFER TO BG?
classes_idxs_new.remove(0)
##############################
desired_noise = int(random.sample(classes_idxs_new, 1)[0])
if desired_noise != 0:
obj[0].text = voc2007.CLASSES[desired_noise]
else:
root.remove(obj)
tree.write(os.path.join(noisy_anno_dir, instance), 'UTF-8')
print('Done generating for idn in dataset {}!'.format(VOC_dir))
if __name__ == "__main__":
generate_sym_noise('./GLRC', "train_fed", 0.75)