-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathpreparation.py
198 lines (165 loc) · 8.65 KB
/
preparation.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
from functools import partial
import multiprocessing as mp
import os
import numpy as np
from imageio import imwrite
from pycocotools import mask as cocomask
from pycocotools.coco import COCO
from skimage.morphology import binary_erosion, rectangle, binary_dilation
from scipy.ndimage.morphology import distance_transform_edt
from sklearn.externals import joblib
from .utils import get_logger, add_dropped_objects, label
logger = get_logger()
def overlay_masks(data_dir, dataset, target_dir, category_ids, erode=0, dilate=0, is_small=False, num_threads=1,
border_width=0, small_annotations_size=14):
if is_small:
suffix = "-small"
else:
suffix = ""
annotation_file_name = "annotation{}.json".format(suffix)
annotation_file_path = os.path.join(data_dir, dataset, annotation_file_name)
coco = COCO(annotation_file_path)
image_ids = coco.getImgIds()
_overlay_mask_one_image = partial(overlay_mask_one_image,
dataset=dataset,
target_dir=target_dir,
coco=coco,
category_ids=category_ids,
erode=erode,
dilate=dilate,
border_width=border_width,
small_annotations_size=small_annotations_size)
process_nr = min(num_threads, len(image_ids))
with mp.pool.ThreadPool(process_nr) as executor:
executor.map(_overlay_mask_one_image, image_ids)
def overlay_mask_one_image(image_id, dataset, target_dir, coco, category_ids, erode, dilate, border_width,
small_annotations_size):
image = coco.loadImgs(image_id)[0]
image_size = (image["height"], image["width"])
mask_overlayed = np.zeros(image_size).astype('uint8')
distances = np.zeros(image_size)
for category_nr, category_id in enumerate(category_ids):
if category_id is not None:
annotation_ids = coco.getAnnIds(imgIds=image_id, catIds=[category_id, ])
annotations = coco.loadAnns(annotation_ids)
if erode < 0 or dilate < 0:
raise ValueError('erode and dilate cannot be negative')
if erode == 0:
mask, distances = overlay_masks_from_annotations(annotations=annotations,
image_size=image_size,
distances=distances)
elif dilate == 0:
mask, _ = overlay_masks_from_annotations(annotations=annotations,
image_size=image_size)
mask_eroded, distances = overlay_eroded_masks_from_annotations(annotations=annotations,
image_size=image_size,
erode=erode,
distances=distances,
small_annotations_size=small_annotations_size)
mask = add_dropped_objects(mask, mask_eroded)
else:
mask, distances = overlay_eroded_dilated_masks_from_annotations(annotations=annotations,
image_size=image_size,
erode=erode,
dilate=dilate,
distances=distances,
small_annotations_size=small_annotations_size)
mask_overlayed = np.where(mask, category_nr, mask_overlayed)
sizes = get_size_matrix(mask_overlayed)
distances, second_nearest_distances = clean_distances(distances)
if border_width > 0:
borders = (second_nearest_distances < border_width) & (~mask_overlayed)
borders_class_id = mask_overlayed.max() + 1
mask_overlayed = np.where(borders, borders_class_id, mask_overlayed)
target_filepath = os.path.join(target_dir, dataset, "masks", os.path.splitext(image["file_name"])[0]) + ".png"
target_filepath_dist = os.path.join(target_dir, dataset, "distances", os.path.splitext(image["file_name"])[0])
target_filepath_sizes = os.path.join(target_dir, dataset, "sizes", os.path.splitext(image["file_name"])[0])
os.makedirs(os.path.dirname(target_filepath), exist_ok=True)
os.makedirs(os.path.dirname(target_filepath_dist), exist_ok=True)
os.makedirs(os.path.dirname(target_filepath_sizes), exist_ok=True)
try:
imwrite(target_filepath, mask_overlayed)
joblib.dump(distances, target_filepath_dist)
joblib.dump(sizes, target_filepath_sizes)
except:
logger.info("Failed to save image: {}".format(image_id))
def overlay_masks_from_annotations(annotations, image_size, distances=None):
mask = np.zeros(image_size)
for ann in annotations:
rle = cocomask.frPyObjects(ann['segmentation'], image_size[0], image_size[1])
m = cocomask.decode(rle)
for i in range(m.shape[-1]):
mi = m[:, :, i]
mi = mi.reshape(image_size)
if is_on_border(mi, 2):
continue
if distances is not None:
distances = update_distances(distances, mi)
mask += mi
return np.where(mask > 0, 1, 0).astype('uint8'), distances
def overlay_eroded_masks_from_annotations(annotations, image_size, erode, distances, small_annotations_size):
mask = np.zeros(image_size)
for ann in annotations:
rle = cocomask.frPyObjects(ann['segmentation'], image_size[0], image_size[1])
m = cocomask.decode(rle)
m = m.reshape(image_size)
if is_on_border(m, 2):
continue
m_eroded = get_simple_eroded_mask(m, erode, small_annotations_size)
if distances is not None:
distances = update_distances(distances, m_eroded)
mask += m_eroded
return np.where(mask > 0, 1, 0).astype('uint8'), distances
def overlay_eroded_dilated_masks_from_annotations(annotations, image_size, erode, dilate, distances,
small_annotations_size):
mask = np.zeros(image_size)
for ann in annotations:
rle = cocomask.frPyObjects(ann['segmentation'], image_size[0], image_size[1])
m = cocomask.decode(rle)
m = m.reshape(image_size)
if is_on_border(m, 2):
continue
m_ = get_simple_eroded_dilated_mask(m, erode, dilate, small_annotations_size)
if distances is not None:
distances = update_distances(distances, m_)
mask += m_
return np.where(mask > 0, 1, 0).astype('uint8'), distances
def update_distances(dist, mask):
if dist.sum() == 0:
distances = distance_transform_edt(1 - mask)
else:
distances = np.dstack([dist, distance_transform_edt(1 - mask)])
return distances
def clean_distances(distances):
if len(distances.shape) < 3:
distances = np.dstack([distances, distances])
else:
distances.sort(axis=2)
distances = distances[:, :, :2]
second_nearest_distances = distances[:, :, 1]
distances_clean = np.sum(distances, axis=2)
return distances_clean.astype(np.float16), second_nearest_distances
def get_simple_eroded_mask(mask, selem_size, small_annotations_size):
if mask.sum() > small_annotations_size**2:
selem = rectangle(selem_size, selem_size)
mask_eroded = binary_erosion(mask, selem=selem)
else:
mask_eroded = mask
return mask_eroded
def get_simple_eroded_dilated_mask(mask, erode_selem_size, dilate_selem_size, small_annotations_size):
if mask.sum() > small_annotations_size**2:
selem = rectangle(erode_selem_size, erode_selem_size)
mask_ = binary_erosion(mask, selem=selem)
else:
selem = rectangle(dilate_selem_size, dilate_selem_size)
mask_ = binary_dilation(mask, selem=selem)
return mask_
def get_size_matrix(mask):
sizes = np.ones_like(mask)
labeled = label(mask)
for label_nr in range(1, labeled.max() + 1):
label_size = (labeled == label_nr).sum()
sizes = np.where(labeled == label_nr, label_size, sizes)
return sizes
def is_on_border(mask, border_width):
return not np.any(mask[border_width:-border_width, border_width:-border_width])