jkushwaha commited on
Commit
4a2702f
·
verified ·
1 Parent(s): d62bbad

Upload utils.py

Browse files
Files changed (1) hide show
  1. utils.py +897 -0
utils.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import logging
4
+ import math
5
+ import random
6
+ import numpy as np
7
+ import tensorflow as tf
8
+ import scipy
9
+ import skimage.color
10
+ import skimage.io
11
+ import skimage.transform
12
+ import urllib.request
13
+ import shutil
14
+ import warnings
15
+ from distutils.version import LooseVersion
16
+
17
+
18
+
19
+ ############################################################
20
+ # Bounding Boxes
21
+ ############################################################
22
+
23
+ def extract_bboxes(mask):
24
+ """Compute bounding boxes from masks.
25
+ mask: [height, width, num_instances]. Mask pixels are either 1 or 0.
26
+
27
+ Returns: bbox array [num_instances, (y1, x1, y2, x2)].
28
+ """
29
+ boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)
30
+ for i in range(mask.shape[-1]):
31
+ m = mask[:, :, i]
32
+ # Bounding box.
33
+ horizontal_indicies = np.where(np.any(m, axis=0))[0]
34
+ vertical_indicies = np.where(np.any(m, axis=1))[0]
35
+ if horizontal_indicies.shape[0]:
36
+ x1, x2 = horizontal_indicies[[0, -1]]
37
+ y1, y2 = vertical_indicies[[0, -1]]
38
+ # x2 and y2 should not be part of the box. Increment by 1.
39
+ x2 += 1
40
+ y2 += 1
41
+ else:
42
+ # No mask for this instance. Might happen due to
43
+ # resizing or cropping. Set bbox to zeros
44
+ x1, x2, y1, y2 = 0, 0, 0, 0
45
+ boxes[i] = np.array([y1, x1, y2, x2])
46
+ return boxes.astype(np.int32)
47
+
48
+
49
+ def compute_iou(box, boxes, box_area, boxes_area):
50
+ """Calculates IoU of the given box with the array of the given boxes.
51
+ box: 1D vector [y1, x1, y2, x2]
52
+ boxes: [boxes_count, (y1, x1, y2, x2)]
53
+ box_area: float. the area of 'box'
54
+ boxes_area: array of length boxes_count.
55
+
56
+ Note: the areas are passed in rather than calculated here for
57
+ efficiency. Calculate once in the caller to avoid duplicate work.
58
+ """
59
+ # Calculate intersection areas
60
+ y1 = np.maximum(box[0], boxes[:, 0])
61
+ y2 = np.minimum(box[2], boxes[:, 2])
62
+ x1 = np.maximum(box[1], boxes[:, 1])
63
+ x2 = np.minimum(box[3], boxes[:, 3])
64
+ intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)
65
+ union = box_area + boxes_area[:] - intersection[:]
66
+ iou = intersection / union
67
+ return iou
68
+
69
+
70
+ def compute_overlaps(boxes1, boxes2):
71
+ """Computes IoU overlaps between two sets of boxes.
72
+ boxes1, boxes2: [N, (y1, x1, y2, x2)].
73
+
74
+ For better performance, pass the largest set first and the smaller second.
75
+ """
76
+ # Areas of anchors and GT boxes
77
+ area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
78
+ area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
79
+
80
+ # Compute overlaps to generate matrix [boxes1 count, boxes2 count]
81
+ # Each cell contains the IoU value.
82
+ overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0]))
83
+ for i in range(overlaps.shape[1]):
84
+ box2 = boxes2[i]
85
+ overlaps[:, i] = compute_iou(box2, boxes1, area2[i], area1)
86
+ return overlaps
87
+
88
+
89
+ def compute_overlaps_masks(masks1, masks2):
90
+ """Computes IoU overlaps between two sets of masks.
91
+ masks1, masks2: [Height, Width, instances]
92
+ """
93
+
94
+ # If either set of masks is empty return empty result
95
+ if masks1.shape[-1] == 0 or masks2.shape[-1] == 0:
96
+ return np.zeros((masks1.shape[-1], masks2.shape[-1]))
97
+ # flatten masks and compute their areas
98
+ masks1 = np.reshape(masks1 > .5, (-1, masks1.shape[-1])).astype(np.float32)
99
+ masks2 = np.reshape(masks2 > .5, (-1, masks2.shape[-1])).astype(np.float32)
100
+ area1 = np.sum(masks1, axis=0)
101
+ area2 = np.sum(masks2, axis=0)
102
+
103
+ # intersections and union
104
+ intersections = np.dot(masks1.T, masks2)
105
+ union = area1[:, None] + area2[None, :] - intersections
106
+ overlaps = intersections / union
107
+
108
+ return overlaps
109
+
110
+
111
+ def non_max_suppression(boxes, scores, threshold):
112
+ """Performs non-maximum suppression and returns indices of kept boxes.
113
+ boxes: [N, (y1, x1, y2, x2)]. Notice that (y2, x2) lays outside the box.
114
+ scores: 1-D array of box scores.
115
+ threshold: Float. IoU threshold to use for filtering.
116
+ """
117
+ assert boxes.shape[0] > 0
118
+ if boxes.dtype.kind != "f":
119
+ boxes = boxes.astype(np.float32)
120
+
121
+ # Compute box areas
122
+ y1 = boxes[:, 0]
123
+ x1 = boxes[:, 1]
124
+ y2 = boxes[:, 2]
125
+ x2 = boxes[:, 3]
126
+ area = (y2 - y1) * (x2 - x1)
127
+
128
+ # Get indicies of boxes sorted by scores (highest first)
129
+ ixs = scores.argsort()[::-1]
130
+
131
+ pick = []
132
+ while len(ixs) > 0:
133
+ # Pick top box and add its index to the list
134
+ i = ixs[0]
135
+ pick.append(i)
136
+ # Compute IoU of the picked box with the rest
137
+ iou = compute_iou(boxes[i], boxes[ixs[1:]], area[i], area[ixs[1:]])
138
+ # Identify boxes with IoU over the threshold. This
139
+ # returns indices into ixs[1:], so add 1 to get
140
+ # indices into ixs.
141
+ remove_ixs = np.where(iou > threshold)[0] + 1
142
+ # Remove indices of the picked and overlapped boxes.
143
+ ixs = np.delete(ixs, remove_ixs)
144
+ ixs = np.delete(ixs, 0)
145
+ return np.array(pick, dtype=np.int32)
146
+
147
+
148
+ def apply_box_deltas(boxes, deltas):
149
+ """Applies the given deltas to the given boxes.
150
+ boxes: [N, (y1, x1, y2, x2)]. Note that (y2, x2) is outside the box.
151
+ deltas: [N, (dy, dx, log(dh), log(dw))]
152
+ """
153
+ boxes = boxes.astype(np.float32)
154
+ # Convert to y, x, h, w
155
+ height = boxes[:, 2] - boxes[:, 0]
156
+ width = boxes[:, 3] - boxes[:, 1]
157
+ center_y = boxes[:, 0] + 0.5 * height
158
+ center_x = boxes[:, 1] + 0.5 * width
159
+ # Apply deltas
160
+ center_y += deltas[:, 0] * height
161
+ center_x += deltas[:, 1] * width
162
+ height *= np.exp(deltas[:, 2])
163
+ width *= np.exp(deltas[:, 3])
164
+ # Convert back to y1, x1, y2, x2
165
+ y1 = center_y - 0.5 * height
166
+ x1 = center_x - 0.5 * width
167
+ y2 = y1 + height
168
+ x2 = x1 + width
169
+ return np.stack([y1, x1, y2, x2], axis=1)
170
+
171
+
172
+ def box_refinement_graph(box, gt_box):
173
+ """Compute refinement needed to transform box to gt_box.
174
+ box and gt_box are [N, (y1, x1, y2, x2)]
175
+ """
176
+ box = tf.cast(box, tf.float32)
177
+ gt_box = tf.cast(gt_box, tf.float32)
178
+
179
+ height = box[:, 2] - box[:, 0]
180
+ width = box[:, 3] - box[:, 1]
181
+ center_y = box[:, 0] + 0.5 * height
182
+ center_x = box[:, 1] + 0.5 * width
183
+
184
+ gt_height = gt_box[:, 2] - gt_box[:, 0]
185
+ gt_width = gt_box[:, 3] - gt_box[:, 1]
186
+ gt_center_y = gt_box[:, 0] + 0.5 * gt_height
187
+ gt_center_x = gt_box[:, 1] + 0.5 * gt_width
188
+
189
+ dy = (gt_center_y - center_y) / height
190
+ dx = (gt_center_x - center_x) / width
191
+ dh = tf.log(gt_height / height)
192
+ dw = tf.log(gt_width / width)
193
+
194
+ result = tf.stack([dy, dx, dh, dw], axis=1)
195
+ return result
196
+
197
+
198
+ def box_refinement(box, gt_box):
199
+ """Compute refinement needed to transform box to gt_box.
200
+ box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is
201
+ assumed to be outside the box.
202
+ """
203
+ box = box.astype(np.float32)
204
+ gt_box = gt_box.astype(np.float32)
205
+
206
+ height = box[:, 2] - box[:, 0]
207
+ width = box[:, 3] - box[:, 1]
208
+ center_y = box[:, 0] + 0.5 * height
209
+ center_x = box[:, 1] + 0.5 * width
210
+
211
+ gt_height = gt_box[:, 2] - gt_box[:, 0]
212
+ gt_width = gt_box[:, 3] - gt_box[:, 1]
213
+ gt_center_y = gt_box[:, 0] + 0.5 * gt_height
214
+ gt_center_x = gt_box[:, 1] + 0.5 * gt_width
215
+
216
+ dy = (gt_center_y - center_y) / height
217
+ dx = (gt_center_x - center_x) / width
218
+ dh = np.log(gt_height / height)
219
+ dw = np.log(gt_width / width)
220
+
221
+ return np.stack([dy, dx, dh, dw], axis=1)
222
+
223
+
224
+ ############################################################
225
+ # Dataset
226
+ ############################################################
227
+
228
+ class Dataset(object):
229
+ """The base class for dataset classes.
230
+ To use it, create a new class that adds functions specific to the dataset
231
+ you want to use. For example:
232
+
233
+ class CatsAndDogsDataset(Dataset):
234
+ def load_cats_and_dogs(self):
235
+ ...
236
+ def load_mask(self, image_id):
237
+ ...
238
+ def image_reference(self, image_id):
239
+ ...
240
+
241
+ See COCODataset and ShapesDataset as examples.
242
+ """
243
+
244
+ def __init__(self, class_map=None):
245
+ self._image_ids = []
246
+ self.image_info = []
247
+ # Background is always the first class
248
+ self.class_info = [{"source": "", "id": 0, "name": "BG"}]
249
+ self.source_class_ids = {}
250
+
251
+ def add_class(self, source, class_id, class_name):
252
+ assert "." not in source, "Source name cannot contain a dot"
253
+ # Does the class exist already?
254
+ for info in self.class_info:
255
+ if info['source'] == source and info["id"] == class_id:
256
+ # source.class_id combination already available, skip
257
+ return
258
+ # Add the class
259
+ self.class_info.append({
260
+ "source": source,
261
+ "id": class_id,
262
+ "name": class_name,
263
+ })
264
+
265
+ def add_image(self, source, image_id, path, **kwargs):
266
+ image_info = {
267
+ "id": image_id,
268
+ "source": source,
269
+ "path": path,
270
+ }
271
+ image_info.update(kwargs)
272
+ self.image_info.append(image_info)
273
+
274
+ def image_reference(self, image_id):
275
+ """Return a link to the image in its source Website or details about
276
+ the image that help looking it up or debugging it.
277
+
278
+ Override for your dataset, but pass to this function
279
+ if you encounter images not in your dataset.
280
+ """
281
+ return ""
282
+
283
+ def prepare(self, class_map=None):
284
+ """Prepares the Dataset class for use.
285
+
286
+ TODO: class map is not supported yet. When done, it should handle mapping
287
+ classes from different datasets to the same class ID.
288
+ """
289
+
290
+ def clean_name(name):
291
+ """Returns a shorter version of object names for cleaner display."""
292
+ return ",".join(name.split(",")[:1])
293
+
294
+ # Build (or rebuild) everything else from the info dicts.
295
+ self.num_classes = len(self.class_info)
296
+ self.class_ids = np.arange(self.num_classes)
297
+ self.class_names = [clean_name(c["name"]) for c in self.class_info]
298
+ self.num_images = len(self.image_info)
299
+ self._image_ids = np.arange(self.num_images)
300
+
301
+ # Mapping from source class and image IDs to internal IDs
302
+ self.class_from_source_map = {"{}.{}".format(info['source'], info['id']): id
303
+ for info, id in zip(self.class_info, self.class_ids)}
304
+ self.image_from_source_map = {"{}.{}".format(info['source'], info['id']): id
305
+ for info, id in zip(self.image_info, self.image_ids)}
306
+
307
+ # Map sources to class_ids they support
308
+ self.sources = list(set([i['source'] for i in self.class_info]))
309
+ self.source_class_ids = {}
310
+ # Loop over datasets
311
+ for source in self.sources:
312
+ self.source_class_ids[source] = []
313
+ # Find classes that belong to this dataset
314
+ for i, info in enumerate(self.class_info):
315
+ # Include BG class in all datasets
316
+ if i == 0 or source == info['source']:
317
+ self.source_class_ids[source].append(i)
318
+
319
+ def map_source_class_id(self, source_class_id):
320
+ """Takes a source class ID and returns the int class ID assigned to it.
321
+
322
+ For example:
323
+ dataset.map_source_class_id("coco.12") -> 23
324
+ """
325
+ return self.class_from_source_map[source_class_id]
326
+
327
+ def get_source_class_id(self, class_id, source):
328
+ """Map an internal class ID to the corresponding class ID in the source dataset."""
329
+ info = self.class_info[class_id]
330
+ assert info['source'] == source
331
+ return info['id']
332
+
333
+ @property
334
+ def image_ids(self):
335
+ return self._image_ids
336
+
337
+ def source_image_link(self, image_id):
338
+ """Returns the path or URL to the image.
339
+ Override this to return a URL to the image if it's available online for easy
340
+ debugging.
341
+ """
342
+ return self.image_info[image_id]["path"]
343
+
344
+ def load_image(self, image_id):
345
+ """Load the specified image and return a [H,W,3] Numpy array.
346
+ """
347
+ # Load image
348
+ image = skimage.io.imread(self.image_info[image_id]['path'])
349
+ # If grayscale. Convert to RGB for consistency.
350
+ if image.ndim != 3:
351
+ image = skimage.color.gray2rgb(image)
352
+ # If has an alpha channel, remove it for consistency
353
+ if image.shape[-1] == 4:
354
+ image = image[..., :3]
355
+ return image
356
+
357
+ def load_mask(self, image_id):
358
+ """Load instance masks for the given image.
359
+
360
+ Different datasets use different ways to store masks. Override this
361
+ method to load instance masks and return them in the form of am
362
+ array of binary masks of shape [height, width, instances].
363
+
364
+ Returns:
365
+ masks: A bool array of shape [height, width, instance count] with
366
+ a binary mask per instance.
367
+ class_ids: a 1D array of class IDs of the instance masks.
368
+ """
369
+ # Override this function to load a mask from your dataset.
370
+ # Otherwise, it returns an empty mask.
371
+ logging.warning("You are using the default load_mask(), maybe you need to define your own one.")
372
+ mask = np.empty([0, 0, 0])
373
+ class_ids = np.empty([0], np.int32)
374
+ return mask, class_ids
375
+
376
+
377
+ def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"):
378
+ """Resizes an image keeping the aspect ratio unchanged.
379
+
380
+ min_dim: if provided, resizes the image such that it's smaller
381
+ dimension == min_dim
382
+ max_dim: if provided, ensures that the image longest side doesn't
383
+ exceed this value.
384
+ min_scale: if provided, ensure that the image is scaled up by at least
385
+ this percent even if min_dim doesn't require it.
386
+ mode: Resizing mode.
387
+ none: No resizing. Return the image unchanged.
388
+ square: Resize and pad with zeros to get a square image
389
+ of size [max_dim, max_dim].
390
+ pad64: Pads width and height with zeros to make them multiples of 64.
391
+ If min_dim or min_scale are provided, it scales the image up
392
+ before padding. max_dim is ignored in this mode.
393
+ The multiple of 64 is needed to ensure smooth scaling of feature
394
+ maps up and down the 6 levels of the FPN pyramid (2**6=64).
395
+ crop: Picks random crops from the image. First, scales the image based
396
+ on min_dim and min_scale, then picks a random crop of
397
+ size min_dim x min_dim. Can be used in training only.
398
+ max_dim is not used in this mode.
399
+
400
+ Returns:
401
+ image: the resized image
402
+ window: (y1, x1, y2, x2). If max_dim is provided, padding might
403
+ be inserted in the returned image. If so, this window is the
404
+ coordinates of the image part of the full image (excluding
405
+ the padding). The x2, y2 pixels are not included.
406
+ scale: The scale factor used to resize the image
407
+ padding: Padding added to the image [(top, bottom), (left, right), (0, 0)]
408
+ """
409
+ # Keep track of image dtype and return results in the same dtype
410
+ image_dtype = image.dtype
411
+ # Default window (y1, x1, y2, x2) and default scale == 1.
412
+ h, w = image.shape[:2]
413
+ window = (0, 0, h, w)
414
+ scale = 1
415
+ padding = [(0, 0), (0, 0), (0, 0)]
416
+ crop = None
417
+
418
+ if mode == "none":
419
+ return image, window, scale, padding, crop
420
+
421
+ # Scale?
422
+ if min_dim:
423
+ # Scale up but not down
424
+ scale = max(1, min_dim / min(h, w))
425
+ if min_scale and scale < min_scale:
426
+ scale = min_scale
427
+
428
+ # Does it exceed max dim?
429
+ if max_dim and mode == "square":
430
+ image_max = max(h, w)
431
+ if round(image_max * scale) > max_dim:
432
+ scale = max_dim / image_max
433
+
434
+ # Resize image using bilinear interpolation
435
+ if scale != 1:
436
+ image = resize(image, (round(h * scale), round(w * scale)),
437
+ preserve_range=True)
438
+
439
+ # Need padding or cropping?
440
+ if mode == "square":
441
+ # Get new height and width
442
+ h, w = image.shape[:2]
443
+ top_pad = (max_dim - h) // 2
444
+ bottom_pad = max_dim - h - top_pad
445
+ left_pad = (max_dim - w) // 2
446
+ right_pad = max_dim - w - left_pad
447
+ padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
448
+ image = np.pad(image, padding, mode='constant', constant_values=0)
449
+ window = (top_pad, left_pad, h + top_pad, w + left_pad)
450
+ elif mode == "pad64":
451
+ h, w = image.shape[:2]
452
+ # Both sides must be divisible by 64
453
+ assert min_dim % 64 == 0, "Minimum dimension must be a multiple of 64"
454
+ # Height
455
+ if h % 64 > 0:
456
+ max_h = h - (h % 64) + 64
457
+ top_pad = (max_h - h) // 2
458
+ bottom_pad = max_h - h - top_pad
459
+ else:
460
+ top_pad = bottom_pad = 0
461
+ # Width
462
+ if w % 64 > 0:
463
+ max_w = w - (w % 64) + 64
464
+ left_pad = (max_w - w) // 2
465
+ right_pad = max_w - w - left_pad
466
+ else:
467
+ left_pad = right_pad = 0
468
+ padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
469
+ image = np.pad(image, padding, mode='constant', constant_values=0)
470
+ window = (top_pad, left_pad, h + top_pad, w + left_pad)
471
+ elif mode == "crop":
472
+ # Pick a random crop
473
+ h, w = image.shape[:2]
474
+ y = random.randint(0, (h - min_dim))
475
+ x = random.randint(0, (w - min_dim))
476
+ crop = (y, x, min_dim, min_dim)
477
+ image = image[y:y + min_dim, x:x + min_dim]
478
+ window = (0, 0, min_dim, min_dim)
479
+ else:
480
+ raise Exception("Mode {} not supported".format(mode))
481
+ return image.astype(image_dtype), window, scale, padding, crop
482
+
483
+
484
+ def resize_mask(mask, scale, padding, crop=None):
485
+ """Resizes a mask using the given scale and padding.
486
+ Typically, you get the scale and padding from resize_image() to
487
+ ensure both, the image and the mask, are resized consistently.
488
+
489
+ scale: mask scaling factor
490
+ padding: Padding to add to the mask in the form
491
+ [(top, bottom), (left, right), (0, 0)]
492
+ """
493
+ # Suppress warning from scipy 0.13.0, the output shape of zoom() is
494
+ # calculated with round() instead of int()
495
+ with warnings.catch_warnings():
496
+ warnings.simplefilter("ignore")
497
+ mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0)
498
+ if crop is not None:
499
+ y, x, h, w = crop
500
+ mask = mask[y:y + h, x:x + w]
501
+ else:
502
+ mask = np.pad(mask, padding, mode='constant', constant_values=0)
503
+ return mask
504
+
505
+
506
+ def minimize_mask(bbox, mask, mini_shape):
507
+ """Resize masks to a smaller version to reduce memory load.
508
+ Mini-masks can be resized back to image scale using expand_masks()
509
+
510
+ See inspect_data.ipynb notebook for more details.
511
+ """
512
+ mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
513
+ for i in range(mask.shape[-1]):
514
+ # Pick slice and cast to bool in case load_mask() returned wrong dtype
515
+ m = mask[:, :, i].astype(bool)
516
+ y1, x1, y2, x2 = bbox[i][:4]
517
+ m = m[y1:y2, x1:x2]
518
+ if m.size == 0:
519
+ raise Exception("Invalid bounding box with area of zero")
520
+ # Resize with bilinear interpolation
521
+ m = resize(m, mini_shape)
522
+ mini_mask[:, :, i] = np.around(m).astype(np.bool)
523
+ return mini_mask
524
+
525
+
526
+ def expand_mask(bbox, mini_mask, image_shape):
527
+ """Resizes mini masks back to image size. Reverses the change
528
+ of minimize_mask().
529
+
530
+ See inspect_data.ipynb notebook for more details.
531
+ """
532
+ mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
533
+ for i in range(mask.shape[-1]):
534
+ m = mini_mask[:, :, i]
535
+ y1, x1, y2, x2 = bbox[i][:4]
536
+ h = y2 - y1
537
+ w = x2 - x1
538
+ # Resize with bilinear interpolation
539
+ m = resize(m, (h, w))
540
+ mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
541
+ return mask
542
+
543
+
544
+ # TODO: Build and use this function to reduce code duplication
545
+ def mold_mask(mask, config):
546
+ pass
547
+
548
+
549
+ def unmold_mask(mask, bbox, image_shape):
550
+ """Converts a mask generated by the neural network to a format similar
551
+ to its original shape.
552
+ mask: [height, width] of type float. A small, typically 28x28 mask.
553
+ bbox: [y1, x1, y2, x2]. The box to fit the mask in.
554
+
555
+ Returns a binary mask with the same size as the original image.
556
+ """
557
+ threshold = 0.5
558
+ y1, x1, y2, x2 = bbox
559
+ mask = resize(mask, (y2 - y1, x2 - x1))
560
+ mask = np.where(mask >= threshold, 1, 0).astype(np.bool)
561
+
562
+ # Put the mask in the right location.
563
+ full_mask = np.zeros(image_shape[:2], dtype=np.bool)
564
+ full_mask[y1:y2, x1:x2] = mask
565
+ return full_mask
566
+
567
+
568
+ ############################################################
569
+ # Anchors
570
+ ############################################################
571
+
572
+ def generate_anchors(scales, ratios, shape, feature_stride, anchor_stride):
573
+ """
574
+ scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128]
575
+ ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2]
576
+ shape: [height, width] spatial shape of the feature map over which
577
+ to generate anchors.
578
+ feature_stride: Stride of the feature map relative to the image in pixels.
579
+ anchor_stride: Stride of anchors on the feature map. For example, if the
580
+ value is 2 then generate anchors for every other feature map pixel.
581
+ """
582
+ # Get all combinations of scales and ratios
583
+ scales, ratios = np.meshgrid(np.array(scales), np.array(ratios))
584
+ scales = scales.flatten()
585
+ ratios = ratios.flatten()
586
+
587
+ # Enumerate heights and widths from scales and ratios
588
+ heights = scales / np.sqrt(ratios)
589
+ widths = scales * np.sqrt(ratios)
590
+
591
+ # Enumerate shifts in feature space
592
+ shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride
593
+ shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride
594
+ shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y)
595
+
596
+ # Enumerate combinations of shifts, widths, and heights
597
+ box_widths, box_centers_x = np.meshgrid(widths, shifts_x)
598
+ box_heights, box_centers_y = np.meshgrid(heights, shifts_y)
599
+
600
+ # Reshape to get a list of (y, x) and a list of (h, w)
601
+ box_centers = np.stack(
602
+ [box_centers_y, box_centers_x], axis=2).reshape([-1, 2])
603
+ box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2])
604
+
605
+ # Convert to corner coordinates (y1, x1, y2, x2)
606
+ boxes = np.concatenate([box_centers - 0.5 * box_sizes,
607
+ box_centers + 0.5 * box_sizes], axis=1)
608
+ return boxes
609
+
610
+
611
+ def generate_pyramid_anchors(scales, ratios, feature_shapes, feature_strides,
612
+ anchor_stride):
613
+ """Generate anchors at different levels of a feature pyramid. Each scale
614
+ is associated with a level of the pyramid, but each ratio is used in
615
+ all levels of the pyramid.
616
+
617
+ Returns:
618
+ anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted
619
+ with the same order of the given scales. So, anchors of scale[0] come
620
+ first, then anchors of scale[1], and so on.
621
+ """
622
+ # Anchors
623
+ # [anchor_count, (y1, x1, y2, x2)]
624
+ anchors = []
625
+ for i in range(len(scales)):
626
+ anchors.append(generate_anchors(scales[i], ratios, feature_shapes[i],
627
+ feature_strides[i], anchor_stride))
628
+ return np.concatenate(anchors, axis=0)
629
+
630
+
631
+ ############################################################
632
+ # Miscellaneous
633
+ ############################################################
634
+
635
+ def trim_zeros(x):
636
+ """It's common to have tensors larger than the available data and
637
+ pad with zeros. This function removes rows that are all zeros.
638
+
639
+ x: [rows, columns].
640
+ """
641
+ assert len(x.shape) == 2
642
+ return x[~np.all(x == 0, axis=1)]
643
+
644
+
645
+ def compute_matches(gt_boxes, gt_class_ids, gt_masks,
646
+ pred_boxes, pred_class_ids, pred_scores, pred_masks,
647
+ iou_threshold=0.5, score_threshold=0.0):
648
+ """Finds matches between prediction and ground truth instances.
649
+
650
+ Returns:
651
+ gt_match: 1-D array. For each GT box it has the index of the matched
652
+ predicted box.
653
+ pred_match: 1-D array. For each predicted box, it has the index of
654
+ the matched ground truth box.
655
+ overlaps: [pred_boxes, gt_boxes] IoU overlaps.
656
+ """
657
+ # Trim zero padding
658
+ # TODO: cleaner to do zero unpadding upstream
659
+ gt_boxes = trim_zeros(gt_boxes)
660
+ gt_masks = gt_masks[..., :gt_boxes.shape[0]]
661
+ pred_boxes = trim_zeros(pred_boxes)
662
+ pred_scores = pred_scores[:pred_boxes.shape[0]]
663
+ # Sort predictions by score from high to low
664
+ indices = np.argsort(pred_scores)[::-1]
665
+ pred_boxes = pred_boxes[indices]
666
+ pred_class_ids = pred_class_ids[indices]
667
+ pred_scores = pred_scores[indices]
668
+ pred_masks = pred_masks[..., indices]
669
+
670
+ # Compute IoU overlaps [pred_masks, gt_masks]
671
+ overlaps = compute_overlaps_masks(pred_masks, gt_masks)
672
+
673
+ # Loop through predictions and find matching ground truth boxes
674
+ match_count = 0
675
+ pred_match = -1 * np.ones([pred_boxes.shape[0]])
676
+ gt_match = -1 * np.ones([gt_boxes.shape[0]])
677
+ for i in range(len(pred_boxes)):
678
+ # Find best matching ground truth box
679
+ # 1. Sort matches by score
680
+ sorted_ixs = np.argsort(overlaps[i])[::-1]
681
+ # 2. Remove low scores
682
+ low_score_idx = np.where(overlaps[i, sorted_ixs] < score_threshold)[0]
683
+ if low_score_idx.size > 0:
684
+ sorted_ixs = sorted_ixs[:low_score_idx[0]]
685
+ # 3. Find the match
686
+ for j in sorted_ixs:
687
+ # If ground truth box is already matched, go to next one
688
+ if gt_match[j] > -1:
689
+ continue
690
+ # If we reach IoU smaller than the threshold, end the loop
691
+ iou = overlaps[i, j]
692
+ if iou < iou_threshold:
693
+ break
694
+ # Do we have a match?
695
+ if pred_class_ids[i] == gt_class_ids[j]:
696
+ match_count += 1
697
+ gt_match[j] = i
698
+ pred_match[i] = j
699
+ break
700
+
701
+ return gt_match, pred_match, overlaps
702
+
703
+
704
+ def compute_ap(gt_boxes, gt_class_ids, gt_masks,
705
+ pred_boxes, pred_class_ids, pred_scores, pred_masks,
706
+ iou_threshold=0.5):
707
+ """Compute Average Precision at a set IoU threshold (default 0.5).
708
+
709
+ Returns:
710
+ mAP: Mean Average Precision
711
+ precisions: List of precisions at different class score thresholds.
712
+ recalls: List of recall values at different class score thresholds.
713
+ overlaps: [pred_boxes, gt_boxes] IoU overlaps.
714
+ """
715
+ # Get matches and overlaps
716
+ gt_match, pred_match, overlaps = compute_matches(
717
+ gt_boxes, gt_class_ids, gt_masks,
718
+ pred_boxes, pred_class_ids, pred_scores, pred_masks,
719
+ iou_threshold)
720
+
721
+ # Compute precision and recall at each prediction box step
722
+ precisions = np.cumsum(pred_match > -1) / (np.arange(len(pred_match)) + 1)
723
+ recalls = np.cumsum(pred_match > -1).astype(np.float32) / len(gt_match)
724
+
725
+ # Pad with start and end values to simplify the math
726
+ precisions = np.concatenate([[0], precisions, [0]])
727
+ recalls = np.concatenate([[0], recalls, [1]])
728
+
729
+ # Ensure precision values decrease but don't increase. This way, the
730
+ # precision value at each recall threshold is the maximum it can be
731
+ # for all following recall thresholds, as specified by the VOC paper.
732
+ for i in range(len(precisions) - 2, -1, -1):
733
+ precisions[i] = np.maximum(precisions[i], precisions[i + 1])
734
+
735
+ # Compute mean AP over recall range
736
+ indices = np.where(recalls[:-1] != recalls[1:])[0] + 1
737
+ mAP = np.sum((recalls[indices] - recalls[indices - 1]) *
738
+ precisions[indices])
739
+
740
+ return mAP, precisions, recalls, overlaps
741
+
742
+
743
+ def compute_ap_range(gt_box, gt_class_id, gt_mask,
744
+ pred_box, pred_class_id, pred_score, pred_mask,
745
+ iou_thresholds=None, verbose=1):
746
+ """Compute AP over a range or IoU thresholds. Default range is 0.5-0.95."""
747
+ # Default is 0.5 to 0.95 with increments of 0.05
748
+ iou_thresholds = iou_thresholds or np.arange(0.5, 1.0, 0.05)
749
+
750
+ # Compute AP over range of IoU thresholds
751
+ AP = []
752
+ for iou_threshold in iou_thresholds:
753
+ ap, precisions, recalls, overlaps =\
754
+ compute_ap(gt_box, gt_class_id, gt_mask,
755
+ pred_box, pred_class_id, pred_score, pred_mask,
756
+ iou_threshold=iou_threshold)
757
+ if verbose:
758
+ print("AP @{:.2f}:\t {:.3f}".format(iou_threshold, ap))
759
+ AP.append(ap)
760
+ AP = np.array(AP).mean()
761
+ if verbose:
762
+ print("AP @{:.2f}-{:.2f}:\t {:.3f}".format(
763
+ iou_thresholds[0], iou_thresholds[-1], AP))
764
+ return AP
765
+
766
+
767
+ def compute_recall(pred_boxes, gt_boxes, iou):
768
+ """Compute the recall at the given IoU threshold. It's an indication
769
+ of how many GT boxes were found by the given prediction boxes.
770
+
771
+ pred_boxes: [N, (y1, x1, y2, x2)] in image coordinates
772
+ gt_boxes: [N, (y1, x1, y2, x2)] in image coordinates
773
+ """
774
+ # Measure overlaps
775
+ overlaps = compute_overlaps(pred_boxes, gt_boxes)
776
+ iou_max = np.max(overlaps, axis=1)
777
+ iou_argmax = np.argmax(overlaps, axis=1)
778
+ positive_ids = np.where(iou_max >= iou)[0]
779
+ matched_gt_boxes = iou_argmax[positive_ids]
780
+
781
+ recall = len(set(matched_gt_boxes)) / gt_boxes.shape[0]
782
+ return recall, positive_ids
783
+
784
+
785
+ # ## Batch Slicing
786
+ # Some custom layers support a batch size of 1 only, and require a lot of work
787
+ # to support batches greater than 1. This function slices an input tensor
788
+ # across the batch dimension and feeds batches of size 1. Effectively,
789
+ # an easy way to support batches > 1 quickly with little code modification.
790
+ # In the long run, it's more efficient to modify the code to support large
791
+ # batches and getting rid of this function. Consider this a temporary solution
792
+ def batch_slice(inputs, graph_fn, batch_size, names=None):
793
+ """Splits inputs into slices and feeds each slice to a copy of the given
794
+ computation graph and then combines the results. It allows you to run a
795
+ graph on a batch of inputs even if the graph is written to support one
796
+ instance only.
797
+
798
+ inputs: list of tensors. All must have the same first dimension length
799
+ graph_fn: A function that returns a TF tensor that's part of a graph.
800
+ batch_size: number of slices to divide the data into.
801
+ names: If provided, assigns names to the resulting tensors.
802
+ """
803
+ if not isinstance(inputs, list):
804
+ inputs = [inputs]
805
+
806
+ outputs = []
807
+ for i in range(batch_size):
808
+ inputs_slice = [x[i] for x in inputs]
809
+ output_slice = graph_fn(*inputs_slice)
810
+ if not isinstance(output_slice, (tuple, list)):
811
+ output_slice = [output_slice]
812
+ outputs.append(output_slice)
813
+ # Change outputs from a list of slices where each is
814
+ # a list of outputs to a list of outputs and each has
815
+ # a list of slices
816
+ outputs = list(zip(*outputs))
817
+
818
+ if names is None:
819
+ names = [None] * len(outputs)
820
+
821
+ result = [tf.stack(o, axis=0, name=n)
822
+ for o, n in zip(outputs, names)]
823
+ if len(result) == 1:
824
+ result = result[0]
825
+
826
+ return result
827
+
828
+
829
+ def download_trained_weights(coco_model_path, verbose=1):
830
+ """Download COCO trained weights from Releases.
831
+
832
+ coco_model_path: local path of COCO trained weights
833
+ """
834
+ if verbose > 0:
835
+ print("Downloading pretrained model to " + coco_model_path + " ...")
836
+ with urllib.request.urlopen(COCO_MODEL_URL) as resp, open(coco_model_path, 'wb') as out:
837
+ shutil.copyfileobj(resp, out)
838
+ if verbose > 0:
839
+ print("... done downloading pretrained model!")
840
+
841
+
842
+ def norm_boxes(boxes, shape):
843
+ """Converts boxes from pixel coordinates to normalized coordinates.
844
+ boxes: [N, (y1, x1, y2, x2)] in pixel coordinates
845
+ shape: [..., (height, width)] in pixels
846
+
847
+ Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
848
+ coordinates it's inside the box.
849
+
850
+ Returns:
851
+ [N, (y1, x1, y2, x2)] in normalized coordinates
852
+ """
853
+ h, w = shape
854
+ scale = np.array([h - 1, w - 1, h - 1, w - 1])
855
+ shift = np.array([0, 0, 1, 1])
856
+ return np.divide((boxes - shift), scale).astype(np.float32)
857
+
858
+
859
+ def denorm_boxes(boxes, shape):
860
+ """Converts boxes from normalized coordinates to pixel coordinates.
861
+ boxes: [N, (y1, x1, y2, x2)] in normalized coordinates
862
+ shape: [..., (height, width)] in pixels
863
+
864
+ Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
865
+ coordinates it's inside the box.
866
+
867
+ Returns:
868
+ [N, (y1, x1, y2, x2)] in pixel coordinates
869
+ """
870
+ h, w = shape
871
+ scale = np.array([h - 1, w - 1, h - 1, w - 1])
872
+ shift = np.array([0, 0, 1, 1])
873
+ return np.around(np.multiply(boxes, scale) + shift).astype(np.int32)
874
+
875
+
876
+ def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True,
877
+ preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None):
878
+ """A wrapper for Scikit-Image resize().
879
+
880
+ Scikit-Image generates warnings on every call to resize() if it doesn't
881
+ receive the right parameters. The right parameters depend on the version
882
+ of skimage. This solves the problem by using different parameters per
883
+ version. And it provides a central place to control resizing defaults.
884
+ """
885
+ if LooseVersion(skimage.__version__) >= LooseVersion("0.14"):
886
+ # New in 0.14: anti_aliasing. Default it to False for backward
887
+ # compatibility with skimage 0.13.
888
+ return skimage.transform.resize(
889
+ image, output_shape,
890
+ order=order, mode=mode, cval=cval, clip=clip,
891
+ preserve_range=preserve_range, anti_aliasing=anti_aliasing,
892
+ anti_aliasing_sigma=anti_aliasing_sigma)
893
+ else:
894
+ return skimage.transform.resize(
895
+ image, output_shape,
896
+ order=order, mode=mode, cval=cval, clip=clip,
897
+ preserve_range=preserve_range)