-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
executable file
·1787 lines (1391 loc) · 64.1 KB
/
utils.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright (c) 2017 Matterport, Inc.
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license
(https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import sys
import os
import time
import math
import random
import numpy as np
import cv2
import utils
cv2.setNumThreads(0)
import torch
import torch.nn.functional as F
import torchvision
from pytorch_lightning.profiler import PassThroughProfiler
import itertools
from skimage.measure import find_contours
import utils_cpp_py
############################################################
# Bounding Boxes
############################################################
def extract_bboxes(mask):
"""Compute bounding boxes from masks.
mask: [height, width, num_instances]. Mask pixels are either 1 or 0.
Returns: bbox array [num_instances, (y1, x1, y2, x2)].
"""
boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)
for i in range(mask.shape[-1]):
m = mask[:, :, i]
## Bounding box.
horizontal_indicies = np.where(np.any(m, axis=0))[0]
vertical_indicies = np.where(np.any(m, axis=1))[0]
if horizontal_indicies.shape[0]:
x1, x2 = horizontal_indicies[[0, -1]]
y1, y2 = vertical_indicies[[0, -1]]
## x2 and y2 should not be part of the box. Increment by 1.
x2 += 1
y2 += 1
else:
## No mask for this instance. Might happen due to
## resizing or cropping. Set bbox to zeros
x1, x2, y1, y2 = 0, 0, 0, 0
boxes[i] = np.array([y1, x1, y2, x2])
return boxes.astype(np.int32)
def compute_iou(box, boxes, box_area, boxes_area):
"""Calculates IoU of the given box with the array of the given boxes.
box: 1D vector [y1, x1, y2, x2]
boxes: [boxes_count, (y1, x1, y2, x2)]
box_area: float. the area of 'box'
boxes_area: array of length boxes_count.
Note: the areas are passed in rather than calculated here for
efficency. Calculate once in the caller to avoid duplicate work.
"""
## Calculate intersection areas
y1 = np.maximum(box[0], boxes[:, 0])
y2 = np.minimum(box[2], boxes[:, 2])
x1 = np.maximum(box[1], boxes[:, 1])
x2 = np.minimum(box[3], boxes[:, 3])
intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)
union = box_area + boxes_area[:] - intersection[:]
iou = intersection / union
return iou
def compute_overlaps(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
For better performance, pass the largest set first and the smaller second.
"""
## Areas of anchors and GT boxes
area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
## Compute overlaps to generate matrix [boxes1 count, boxes2 count]
## Each cell contains the IoU value.
overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0]))
for i in range(overlaps.shape[1]):
box2 = boxes2[i]
overlaps[:, i] = compute_iou(box2, boxes1, area2[i], area1)
return overlaps
def box_refinement(box, gt_box):
"""Compute refinement needed to transform box to gt_box.
box and gt_box are [N, (y1, x1, y2, x2)]
"""
height = box[:, 2] - box[:, 0]
width = box[:, 3] - box[:, 1]
center_y = box[:, 0] + 0.5 * height
center_x = box[:, 1] + 0.5 * width
gt_height = gt_box[:, 2] - gt_box[:, 0]
gt_width = gt_box[:, 3] - gt_box[:, 1]
gt_center_y = gt_box[:, 0] + 0.5 * gt_height
gt_center_x = gt_box[:, 1] + 0.5 * gt_width
dy = (gt_center_y - center_y) / height
dx = (gt_center_x - center_x) / width
dh = torch.log(gt_height / height)
dw = torch.log(gt_width / width)
result = torch.stack([dy, dx, dh, dw], dim=1)
return result
############################################################
# Dataset
############################################################
def resize_image(image, min_dim=None, max_dim=None, padding=False, interp='bilinear'):
"""
Resizes an image keeping the aspect ratio.
min_dim: if provided, resizes the image such that it's smaller
dimension == min_dim
max_dim: if provided, ensures that the image longest side doesn't
exceed this value.
padding: If true, pads image with zeros so it's size is max_dim x max_dim
Returns:
image: the resized image
window: (y1, x1, y2, x2). If max_dim is provided, padding might
be inserted in the returned image. If so, this window is the
coordinates of the image part of the full image (excluding
the padding). The x2, y2 pixels are not included.
scale: The scale factor used to resize the image
padding: Padding added to the image [(top, bottom), (left, right), (0, 0)]
"""
## Default window (y1, x1, y2, x2) and default scale == 1.
h, w = image.shape[:2]
window = (0, 0, h, w)
scale = 1
## Scale?
if min_dim:
# Scale up but not down
scale = max(1, min_dim / min(h, w))
## Does it exceed max dim?
if max_dim:
image_max = max(h, w)
if round(image_max * scale) > max_dim:
scale = max_dim / image_max
## Resize image and mask
if scale != 1:
image = cv2.resize(image, (image.shape[1] * scale, image.shape[0] * scale))
## Need padding?
if padding:
## Get new height and width
h, w = image.shape[:2]
top_pad = (min_dim - h) // 2
bottom_pad = min_dim - h - top_pad
left_pad = (max_dim - w) // 2
right_pad = max_dim - w - left_pad
padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
image = np.pad(image, padding, mode='constant', constant_values=0)
window = (top_pad, left_pad, h + top_pad, w + left_pad)
return image, window, scale, padding
def resize_mask(mask, scale, padding):
"""Resizes a mask using the given scale and padding.
Typically, you get the scale and padding from resize_image() to
ensure both, the image and the mask, are resized consistently.
scale: mask scaling factor
padding: Padding to add to the mask in the form
[(top, bottom), (left, right), (0, 0)]
"""
h, w = mask.shape[:2]
mask = np.pad(mask, padding, mode='constant', constant_values=0)
return mask
def minimize_mask(bbox, mask, mini_shape):
"""Resize masks to a smaller version to cut memory load.
Mini-masks can then resized back to image scale using expand_masks()
See inspect_data.ipynb notebook for more details.
"""
mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
for i in range(mask.shape[-1]):
m = mask[:, :, i]
y1, x1, y2, x2 = bbox[i][:4]
m = m[y1:y2, x1:x2]
if m.size == 0:
raise Exception("Invalid bounding box with area of zero")
m = cv2.resize(m.astype(np.uint8) * 255, mini_shape)
mini_mask[:, :, i] = np.where(m >= 128, 1, 0)
return mini_mask
############################################################
# Anchors
############################################################
def generate_anchors(scales, ratios, shape, feature_stride, anchor_stride):
"""
scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128]
ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2]
shape: [height, width] spatial shape of the feature map over which
to generate anchors.
feature_stride: Stride of the feature map relative to the image in pixels.
anchor_stride: Stride of anchors on the feature map. For example, if the
value is 2 then generate anchors for every other feature map pixel.
"""
## Get all combinations of scales and ratios
scales, ratios = np.meshgrid(np.array(scales), np.array(ratios))
scales = scales.flatten()
ratios = ratios.flatten()
## Enumerate heights and widths from scales and ratios
heights = scales / np.sqrt(ratios)
widths = scales * np.sqrt(ratios)
## Enumerate shifts in feature space
shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride
shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride
shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y)
## Enumerate combinations of shifts, widths, and heights
box_widths, box_centers_x = np.meshgrid(widths, shifts_x)
box_heights, box_centers_y = np.meshgrid(heights, shifts_y)
## Reshape to get a list of (y, x) and a list of (h, w)
box_centers = np.stack(
[box_centers_y, box_centers_x], axis=2).reshape([-1, 2])
box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2])
## Convert to corner coordinates (y1, x1, y2, x2)
boxes = np.concatenate([box_centers - 0.5 * box_sizes,
box_centers + 0.5 * box_sizes], axis=1)
return boxes
def generate_pyramid_anchors(scales, ratios, feature_shapes, feature_strides,
anchor_stride):
"""Generate anchors at different levels of a feature pyramid. Each scale
is associated with a level of the pyramid, but each ratio is used in
all levels of the pyramid.
Returns:
anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted
with the same order of the given scales. So, anchors of scale[0] come
first, then anchors of scale[1], and so on.
"""
## Anchors
## [anchor_count, (y1, x1, y2, x2)]
anchors = []
for i in range(len(scales)):
anchors.append(generate_anchors(scales[i], ratios, feature_shapes[i],
feature_strides[i], anchor_stride))
anchors = np.concatenate(anchors, axis=0)
return anchors
############################################################
# Data Formatting
############################################################
def compose_image_meta(image_id, image_shape, window, active_class_ids):
"""Takes attributes of an image and puts them in one 1D array. Use
parse_image_meta() to parse the values back.
image_id: An int ID of the image. Useful for debugging.
image_shape: [height, width, channels]
window: (y1, x1, y2, x2) in pixels. The area of the image where the real
image is (excluding the padding)
active_class_ids: List of class_ids available in the dataset from which
the image came. Useful if training on images from multiple datasets
where not all classes are present in all datasets.
"""
meta = np.array(
[image_id] + # size=1
list(image_shape) + # size=3
list(window) + # size=4 (y1, x1, y2, x2) in image cooredinates
list(active_class_ids) # size=num_classes
)
return meta
## Two functions (for Numpy and TF) to parse image_meta tensors.
def parse_image_meta_torch(meta):
"""Parses an image info Numpy array to its components.
See compose_image_meta() for more details.
"""
image_id = meta[:, 0]
image_shape = meta[:, 1:4]
window = meta[:, 4:8] # (y1, x1, y2, x2) window of image in in pixels
active_class_ids = meta[:, 8:]
return image_id, image_shape, window, active_class_ids
def parse_image_meta(meta):
"""Parses an image info Numpy array to its components.
See compose_image_meta() for more details.
"""
image_id = meta[0]
image_shape = meta[1:4]
window = meta[4:8] # (y1, x1, y2, x2) window of image in in pixels
active_class_ids = meta[8:]
return image_id, image_shape, window, active_class_ids
def mold_image(images, config):
"""Takes RGB images with 0-255 values and subtraces
the mean pixel and converts it to float. Expects image
colors in RGB order.
"""
return (images.astype(np.float32)/config.SCALE_PIXEL - config.MEAN_PIXEL) / config.STD_PIXEL
def mold_image_torch(images, config):
"""Takes a image normalized with mold() and returns the original."""
# return torch.clamp((normalized_images * config.STD_PIXEL_TENSOR[None, :, None, None] + \
# config.MEAN_PIXEL_TENSOR[None, :, None, None]) * config.SCALE_PIXEL, min=0.0, max=255.0)
return (images / config.SCALE_PIXEL - config.MEAN_PIXEL_TENSOR[None, :, None, None]) / \
config.STD_PIXEL_TENSOR[None, :, None, None]
def unmold_image(normalized_images, config):
"""Takes a image normalized with mold() and returns the original."""
return ((normalized_images * config.STD_PIXEL + config.MEAN_PIXEL) * config.SCALE_PIXEL).astype(np.uint8)
def unmold_image_torch(normalized_images, config):
"""Takes a image normalized with mold() and returns the original."""
# return torch.clamp((normalized_images * config.STD_PIXEL_TENSOR[None, :, None, None] + \
# config.MEAN_PIXEL_TENSOR[None, :, None, None]) * config.SCALE_PIXEL, min=0.0, max=255.0)
return (normalized_images * config.STD_PIXEL_TENSOR[None, :, None, None] + \
config.MEAN_PIXEL_TENSOR[None, :, None, None]) * config.SCALE_PIXEL
def pad_image(image, meta, config, val=0):
im_h = image.shape[0]
im_w = image.shape[1]
im_ch = image.shape[2]
image_id, image_shape, window, active_class_ids = parse_image_meta(meta)
# all windows have to be the same
image_pad = val * np.ones((config.IMAGE_MAX_DIM, config.IMAGE_MAX_DIM, im_ch), dtype=image.dtype)
image_pad[window[0]: window[2], window[1]: window[3], :] = image
return image_pad
def pad_image_torch(image, meta, config, val=0):
im_b = image.shape[0]
im_ch = image.shape[1]
im_h = image.shape[2]
im_w = image.shape[3]
image_id, image_shape, window, active_class_ids = parse_image_meta_torch(meta)
# all windows have to be the same
image_pad = val * torch.ones((im_b, im_ch, config.IMAGE_MAX_DIM, config.IMAGE_MAX_DIM), device=image.device, dtype=image.dtype)
image_pad[:, :, window[0, 0]: window[0, 2], window[0, 1]: window[0, 3]] = image
return image_pad
def crop_image_zeros(image, meta):
image_id, image_shape, window, active_class_ids = parse_image_meta(meta)
# all windows have to be the same
return image[window[0]: window[2], window[1]: window[3], :]
def crop_image_zeros_torch(image, meta):
image_id, image_shape, window, active_class_ids = parse_image_meta_torch(meta)
# all windows have to be the same
return image[:, :, window[0, 0]: window[0, 2], window[0, 1]: window[0, 3]]
def pad_zeros(data, N, dim=0):
zeros_shape = list(data.shape)
zeros_shape[dim] = N - zeros_shape[dim]
return np.concatenate([data, np.zeros(zeros_shape, dtype=data.dtype)], axis=dim)
def pad_zeros_torch(data, N, dim=0):
zeros_shape = list(data.shape)
zeros_shape[dim] = N - zeros_shape[dim]
return torch.cat([data, torch.zeros(zeros_shape, device=data.device, dtype=data.dtype)], dim=dim)
## Visualization
class ColorPalette:
def __init__(self, numColors):
self.colorMap = np.array([[255, 0, 0],
[0, 255, 0],
[0, 0, 255],
[80, 128, 255],
[128, 0, 255],
[255, 0, 255],
[0, 255, 255],
[100, 0, 0],
[0, 100, 0],
[255, 255, 0],
[50, 150, 0],
[200, 255, 255],
[255, 200, 255],
[128, 128, 80],
[0, 50, 128],
[0, 100, 100],
[0, 255, 128],
[0, 128, 255],
[255, 0, 128],
[255, 230, 180],
[255, 128, 0],
[128, 255, 0],
], dtype=np.uint8)
if numColors > self.colorMap.shape[0]:
self.colorMap = np.concatenate([self.colorMap, np.random.randint(255, size = (numColors - self.colorMap.shape[0], 3), dtype=np.uint8)], axis=0)
pass
return
def getColorMap(self, returnTuples=False):
if returnTuples:
return [tuple(color) for color in self.colorMap.tolist()]
else:
return self.colorMap
def getColor(self, index):
if index >= self.colorMap.shape[0]:
return np.random.randint(255, size = (3), dtype=np.uint8)
else:
return self.colorMap[index]
pass
def writePointCloud(filename, point_cloud):
with open(filename, 'w') as f:
header = """ply
format ascii 1.0
element vertex """
header += str(len(point_cloud))
header += """
property float x
property float y
property float z
property uchar red { start of vertex color }
property uchar green
property uchar blue
end_header
"""
f.write(header)
for point in point_cloud:
for valueIndex, value in enumerate(point):
if valueIndex < 3:
f.write(str(value) + ' ')
else:
f.write(str(int(value)) + ' ')
pass
continue
f.write('\n')
continue
f.close()
pass
return
## The function to compute plane depths from plane parameters
def calcPlaneDepths(planes, width, height, camera, max_depth=20):
urange = (np.arange(width, dtype=np.float32).reshape(1, -1).repeat(height, 0) / (width + 1) * (camera[4] + 1) - camera[2]) / camera[0]
vrange = (np.arange(height, dtype=np.float32).reshape(-1, 1).repeat(width, 1) / (height + 1) * (camera[5] + 1) - camera[3]) / camera[1]
ranges = np.stack([urange, vrange, np.ones(urange.shape)], axis=-1)
planeOffsets = np.linalg.norm(planes, axis=-1, keepdims=True)
planeNormals = planes / np.maximum(planeOffsets, 1e-4)
normalXYZ = np.dot(ranges, planeNormals.transpose())
# normalXYZ[normalXYZ < 1e-4] = 1e-4
normalXYZ[normalXYZ == 0] = 1e-4
planeDepths = planeOffsets.squeeze(-1) / normalXYZ
if max_depth > 0:
planeDepths = np.clip(planeDepths, 0, max_depth)
pass
return planeDepths
def to_numpy_image(image):
image_np = image.permute(0, 2, 3, 1).cpu().detach().numpy()
return image_np
def to_torch_image(image_np, dev):
image = torch.from_numpy(image_np).to(dev).permute(0, 3, 1, 2)
return image
def to_torch_image_s(image):
return torch.from_numpy(image.transpose(2, 0, 1)).unsqueeze(0)
def to_numpy_image_s(image):
return image.squeeze(0).permute(1, 2, 0).cpu().numpy()
def draw_depth_images(depth, max_depth=10):
im_b = depth.shape[0]
im_ch = depth.shape[1]
im_h = depth.shape[2]
im_w = depth.shape[3]
depth_np = to_numpy_image(depth)
images = torch.zeros((im_b, 3, im_h, im_w), dtype=torch.uint8, device=depth.device)
for b in range(im_b):
cur_depth = depth_np[b, :, :, 0]
cur_depth = np.clip(cur_depth / max_depth * 255, 0, 255).astype(np.uint8)
cur_depth_img = cv2.applyColorMap(255 - cur_depth, colormap=cv2.COLORMAP_JET)
images[b: b+1, :, :, :] = to_torch_image(cur_depth_img[None, :, :, :], depth.device)
return images
def draw_normal_images(normal):
return torch.clamp((normal + 1.0) / 2.0 * 255.0, min=0, max=255).type(torch.uint8)
# def draw_segmentation_images(image, boxes, masks):
# im_b = image.shape[0]
# im_ch = image.shape[1]
# im_h = image.shape[2]
# im_w = image.shape[3]
#
# box_image = image.copy()
#
# segmentation_image = image * 0.0
# for box, mask in zip(boxes, masks):
# box = np.round(box).astype(np.int32)
# mask = cv2.resize(mask, (box[3] - box[1], box[2] - box[0]))
# segmentation_image[box[0]:box[2], box[1]:box[3]] = np.minimum(
# segmentation_image[box[0]:box[2], box[1]:box[3]] + np.expand_dims(mask,
# axis=-1) * np.random.randint(
# 255, size=(3,), dtype=np.int32), 255)
#
# return segmentation_image
def apply_mask(image, mask, color, alpha=0.5):
"""Apply the given mask to the image.
"""
for c in range(3):
image[:, :, c] = np.where(mask > 0.5,
np.minimum(image[:, :, c] *
(1 - alpha) + alpha * color[c], 255),
image[:, :, c])
def draw_instance_images(config, image, boxes, masks, class_ids, draw_mask=True):
im_b = image.shape[0]
im_ch = image.shape[1]
im_h = image.shape[2]
im_w = image.shape[3]
masked_image = to_numpy_image(image).astype(np.uint8)
for b in range(im_b):
cur_boxes = boxes[b, :, :]
cur_masks = masks[b, :, ...]
cur_class_ids = class_ids[b, :]
cur_masked_image = masked_image[b, :, :, :].copy()
## Number of instances
N = len(cur_boxes)
if not N:
pass
else:
assert cur_boxes.shape[0] == cur_masks.shape[0] == cur_class_ids.shape[0]
## Generate random colors
instance_colors = ColorPalette(N).getColorMap(returnTuples=True)
class_colors = ColorPalette(11).getColorMap(returnTuples=True)
class_colors[0] = (128, 128, 128)
for i in range(N):
## Bounding box
if not (cur_boxes[i, :].long() > 0).any():
# Skip this instance. Has no bbox. Likely lost in image cropping.
continue
y1, x1, y2, x2 = cur_boxes[i, :].cpu().detach().numpy()
## Label
class_id = int(cur_class_ids[i])
if class_id > 0:
## Mask
if len(cur_masks.shape) == 4:
mask = cur_masks[i, class_id, :, :]
elif len(cur_masks.shape) == 3:
mask = cur_masks[i, :, :]
else:
raise Exception('Unsupported mask shape')
mask_full = resize_mask_full(config, cur_boxes[i, :].long(), mask)
mask_full = mask_full.cpu().detach().numpy()
apply_mask(cur_masked_image, mask_full, instance_colors[i])
# cv2.line(cur_masked_image, (0, 0), (511, 511), (255, 0, 0), 5)
#
# pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
# pts = pts.reshape((-1, 1, 2))
# cv2.polylines(cur_masked_image, [pts], True, (0, 255, 255))
## Mask Polygon
## Pad to ensure proper polygons for masks that touch image edges.
if draw_mask:
padded_mask = np.zeros((mask_full.shape[0] + 2, mask_full.shape[1] + 2), dtype=mask_full.dtype)
padded_mask[1:-1, 1:-1] = mask_full
contours = find_contours(padded_mask, 0.5)
for verts in contours:
## Subtract the padding and flip (y, x) to (x, y)
verts = np.fliplr(verts) - 1
cv2.polylines(cur_masked_image, [np.expand_dims(verts.astype(np.int32), 1)], True,
color=class_colors[class_id])
masked_image[b, :, :, :] = cur_masked_image
masked_image = to_torch_image(masked_image, image.device)
return masked_image
def detections_to_normal(config, image, boxes, masks, class_ids, plane_params):
im_b = image.shape[0]
im_ch = image.shape[1]
im_h = image.shape[2]
im_w = image.shape[3]
dev = image.device
normals = torch.zeros((im_b, 3, im_h, im_w), device=dev)
for b in range(im_b):
cur_boxes = boxes[b, :, :]
cur_masks = masks[b, :, ...]
cur_class_ids = class_ids[b, :]
cur_plane_params = plane_params[b, :]
## Number of instances
N = len(cur_boxes)
if not N:
pass
else:
assert cur_boxes.shape[0] == cur_masks.shape[0] == cur_class_ids.shape[0] == cur_plane_params.shape[0]
for i in range(N):
## Bounding box
if not (cur_boxes[i, :].long() > 0).any():
# Skip this instance. Has no bbox. Likely lost in image cropping.
continue
y1, x1, y2, x2 = cur_boxes[i, :].cpu().detach().numpy()
## Label
class_id = int(cur_class_ids[i])
if class_id > 0:
## Mask
if len(cur_masks.shape) == 4:
mask = cur_masks[i, class_id, :, :]
elif len(cur_masks.shape) == 3:
mask = cur_masks[i, :, :]
else:
raise Exception('Unsupported mask shape')
mask_full = resize_mask_full(config, cur_boxes[i, :].long(), mask)
plane_normal = F.normalize(cur_plane_params[i, :], dim=0)
normals[b, :, mask_full > 0.5] = plane_normal.view(-1, 1)
return normals
## Fit a 3D plane from points
def fitPlane(points):
if points.shape[0] == points.shape[1]:
return np.linalg.solve(points, np.ones(points.shape[0]))
else:
return np.linalg.lstsq(points, np.ones(points.shape[0]))[0]
return
## Fit a 3D plane from points
def fitPlaneSVD(points):
centroid = points.mean(axis=0, keepdims=True)
points_demean = points - centroid
[U, S, V] = np.linalg.svd(points_demean, full_matrices=False)
# for the smallest singular value
normal = V[2, :]
d = centroid[0, :].dot(normal)
plane_eq = np.concatenate([normal, [-d]])
return plane_eq
def get_ranges(camera):
fx = camera[0]
fy = camera[1]
cx = camera[2]
cy = camera[3]
w = camera[4]
h = camera[5]
urange = (np.arange(w, dtype=np.float32) - cx) / fx
urange = urange.reshape(1, -1).repeat(h, 0)
vrange = (np.arange(h, dtype=np.float32) - cy) / fy
vrange = vrange.reshape(-1, 1).repeat(w, 1)
ones = np.ones_like(urange)
# ranges = np.stack([urange, ones, -vrange], axis=2)
ranges = np.stack([urange, vrange, ones], axis=2)
return ranges
def get_ranges_torch_batch(camera, dev):
fx = camera[:, 0]
fy = camera[:, 1]
cx = camera[:, 2]
cy = camera[:, 3]
# all images in a batch should have the same dimensions
w = int(camera[0, 4])
h = int(camera[0, 5])
bsize = camera.shape[0]
urange = (torch.arange(w, dtype=camera.dtype, device=dev).view(1, -1) - cx.view(bsize, 1)) / fx.view(bsize, 1)
urange = urange.view(bsize, 1, 1, -1).repeat(1, 1, h, 1)
vrange = (torch.arange(h, dtype=camera.dtype, device=dev).view(1, -1) - cy.view(bsize, 1)) / fy.view(bsize, 1)
vrange = vrange.view(bsize, 1, -1, 1).repeat(1, 1, 1, w)
ones = torch.ones_like(urange)
# ranges = np.stack([urange, ones, -vrange], axis=2)
ranges = torch.cat([urange, vrange, ones], dim=1)
return ranges
def get_ranges_torch(camera, dev):
fx = camera[0]
fy = camera[1]
cx = camera[2]
cy = camera[3]
# all images in a batch should have the same dimensions
w = int(camera[4])
h = int(camera[5])
urange = (torch.arange(w, dtype=camera.dtype, device=dev) - cx) / fx
urange = urange.view(1, 1, 1, -1).repeat(1, 1, h, 1)
vrange = (torch.arange(h, dtype=camera.dtype, device=dev) - cy) / fy
vrange = vrange.view(1, 1, -1, 1).repeat(1, 1, 1, w)
ones = torch.ones_like(urange)
# ranges = np.stack([urange, ones, -vrange], axis=2)
ranges = torch.cat([urange, vrange, ones], dim=1)
return ranges
def get_ranges_pad_torch_batch(camera):
fx = camera[:, 0]
fy = camera[:, 1]
cx = camera[:, 2]
cy = camera[:, 3]
# all images in a batch should have the same dimensions
w = int(camera[0, 4])
h = int(camera[0, 5])
dcy = (w - h) / 2
bsize = camera.shape[0]
dev = camera.device
dtype = camera.dtype
urange = (torch.arange(w, device=dev, dtype=dtype).view(1, -1) - cx.view(bsize, 1)) / fx.view(bsize, 1)
urange = urange.view(bsize, 1, 1, -1).repeat(1, 1, w, 1)
vrange = (torch.arange(w, device=dev, dtype=dtype).view(1, -1) - cy.view(bsize, 1) - dcy) / fy.view(bsize, 1)
vrange = vrange.view(bsize, 1, -1, 1).repeat(1, 1, 1, w)
ones = torch.ones_like(urange)
# ranges = np.stack([urange, ones, -vrange], axis=2)
ranges = torch.cat([urange, vrange, ones], dim=1)
return ranges
def get_ranges_pad_torch(camera):
fx = camera[0]
fy = camera[1]
cx = camera[2]
cy = camera[3]
# all images in a batch should have the same dimensions
w = int(camera[4])
h = int(camera[5])
dcy = (w - h) / 2
dev = camera.device
dtype = camera.dtype
urange = (torch.arange(w, device=dev, dtype=dtype) - cx) / fx
urange = urange.view(1, 1, 1, -1).repeat(1, 1, w, 1)
vrange = (torch.arange(w, device=dev, dtype=dtype) - cy - dcy) / fy
vrange = vrange.view(1, 1, -1, 1).repeat(1, 1, 1, w)
ones = torch.ones_like(urange)
# ranges = np.stack([urange, ones, -vrange], axis=2)
ranges = torch.cat([urange, vrange, ones], dim=1)
return ranges
def get_coords_pad_torch_batch(camera, max_disp, min_disp=5, factor=4):
fx = camera[:, 0].view(-1, 1, 1, 1, 1)
fy = camera[:, 1].view(-1, 1, 1, 1, 1)
cx = camera[:, 2].view(-1, 1, 1, 1, 1)
cy = camera[:, 3].view(-1, 1, 1, 1, 1)
# all images in a batch should have the same dimensions
im_w = int(camera[0, 4])
im_h = int(camera[0, 5])
im_w_f = im_w // factor
im_h_f = im_h // factor
max_disp_f = max_disp // factor
b = camera[:, 6].view(-1, 1, 1, 1, 1)
dcy = (im_w - im_h) / 2
bsize = camera.shape[0]
dev = camera.device
us = torch.arange(0, im_w, step=factor, device=dev, dtype=camera.dtype).view(1, 1, 1, 1, im_w_f) - cx
vs = torch.arange(0, im_w, step=factor, device=dev, dtype=camera.dtype).view(1, 1, 1, im_w_f, 1) - (cy + dcy)
ds = torch.arange(0, max_disp, step=factor, device=dev, dtype=camera.dtype).view(1, 1, max_disp_f, 1, 1)
pts_uvd = torch.cat([us.repeat(1, 1, max_disp_f, im_w_f, 1),
vs.repeat(1, 1, max_disp_f, 1, im_w_f),
ds.repeat(1, 1, 1, im_w_f, im_w_f)], dim=1)
pts_xyz = pts_uvd.new_empty(pts_uvd.shape)
pts_xyz[:, 0:1, :, :, :] = pts_uvd[:, 0:1, :, :, :] * fx * b / torch.clamp(pts_uvd[:, 2:3, :, :, :], min=min_disp) / fx
pts_xyz[:, 1:2, :, :, :] = pts_uvd[:, 1:2, :, :, :] * fx * b / torch.clamp(pts_uvd[:, 2:3, :, :, :], min=min_disp) / fy
pts_xyz[:, 2:3, :, :, :] = fx * b / torch.clamp(pts_uvd[:, 2:3, :, :, :], min=min_disp)
return pts_xyz
def get_coords_uvd_pad_torch_batch(camera, config, max_disp, min_disp=5, factor=4, px=0, py=0):
# all images in a batch should have the same dimensions
im_w = int(camera[0, 4])
im_h = int(camera[0, 5])
im_w_f = im_w // factor
im_h_f = im_h // factor
# px_f = px // factor
# py_f = py // factor
max_disp_f = max_disp // factor
a = config.UVD_CONST
bsize = camera.shape[0]
dev = camera.device
us = torch.arange(0, im_w, step=factor, device=dev, dtype=camera.dtype).view(1, 1, 1, 1, im_w_f) - px
vs = torch.arange(0, im_w, step=factor, device=dev, dtype=camera.dtype).view(1, 1, 1, im_w_f, 1) - py
ds = torch.arange(0, max_disp, step=factor, device=dev, dtype=camera.dtype).view(1, 1, max_disp_f, 1, 1)
pts_uvdun = torch.cat([us.repeat(bsize, 1, max_disp_f, im_w_f, 1),
vs.repeat(bsize, 1, max_disp_f, 1, im_w_f),
ds.repeat(bsize, 1, 1, im_w_f, im_w_f)], dim=1)
pts_uvd = pts_uvdun.new_empty(pts_uvdun.shape)
pts_uvd[:, 0:1, :, :, :] = pts_uvdun[:, 0:1, :, :, :] / torch.clamp(pts_uvdun[:, 2:3, :, :, :], min=min_disp)
pts_uvd[:, 1:2, :, :, :] = pts_uvdun[:, 1:2, :, :, :] / torch.clamp(pts_uvdun[:, 2:3, :, :, :], min=min_disp)
pts_uvd[:, 2:3, :, :, :] = a / torch.clamp(pts_uvd[:, 2:3, :, :, :], min=min_disp)
return pts_uvd
def resize_mask_full(config, box, mask):
dev = mask.device
dtype = mask.dtype
mask = mask.unsqueeze(0).unsqueeze(0)
mask = F.upsample(mask, size=(int(box[2] - box[0]), int(box[3] - box[1])), mode='bilinear')
mask = mask.squeeze(0).squeeze(0)
final_mask = torch.zeros(config.IMAGE_MAX_DIM, config.IMAGE_MAX_DIM, device=dev, dtype=dtype)
final_mask[box[0]:box[2], box[1]:box[3]] = mask
return final_mask
def resize_mask_relative(im_h, im_w, box, mask):
dev = mask.device
dtype = mask.dtype
box_pix = box.clone()
box_pix[[0, 2]] *= im_h
box_pix[[1, 3]] *= im_w
box_pix = box_pix.long()
mask = mask.unsqueeze(0).unsqueeze(0)
mask = F.upsample(mask, size=(box_pix[2] - box_pix[0], box_pix[3] - box_pix[1]), mode='bilinear')
mask = mask.squeeze(0).squeeze(0)
final_mask = torch.zeros(im_h, im_w, device=dev, dtype=dtype)
final_mask[box_pix[0]:box_pix[2], box_pix[1]:box_pix[3]] = mask
return final_mask
def points_to_plane(points, plane):
points = np.concatenate([points, np.ones([points.shape[0], 1])], axis=-1)
diff = points @ plane
return diff
def fit_plane_torch(points):
if points.shape[0] == points.shape[1]:
return torch.solve(torch.ones(points.shape[0], 1, device=points.device), points)[0]
else:
return torch.lstsq(torch.ones(points.shape[0], 1, device=points.device), points)[0][0:3, 0]
return
def fit_plane_ransac(points):
num_iter = 10
plane_diff_threshold = 0.01
best_inliers = 0
best_inliers_mask = None
idxs = np.arange(0, points.shape[0])
for i in range(num_iter):
cur_idxs = np.random.choice(idxs, 3)
cur_points = points[cur_idxs]
try:
cur_plane = fitPlane(cur_points)
except:
continue
# relative distance to the plane
diff = np.abs(np.matmul(points, cur_plane) - np.ones(points.shape[0]))
inlier_mask = diff < plane_diff_threshold
cur_inliers = inlier_mask.sum()
if cur_inliers > best_inliers:
best_inliers = cur_inliers
best_inliers_mask = inlier_mask
# if enough inliers
if cur_inliers / points.shape[0] > 0.95:
break
best_plane = fitPlane(points[best_inliers_mask])
return best_inliers_mask, best_plane
def fit_plane_ransac_torch(points, plane_diff_threshold=0.01, absolute=False):
num_iter = 50
best_inliers = 0
best_inliers_mask = None
for i in range(num_iter):
cur_idxs = torch.randperm(points.shape[0])[:3]
cur_points = points[cur_idxs]
try:
cur_plane = fit_plane_torch(cur_points)
except:
continue
# relative distance to the plane
diff = torch.abs(torch.matmul(points, cur_plane).view(-1) - torch.ones(points.shape[0], device=points.device))
if absolute:
diff = diff / cur_plane.norm()
inlier_mask = diff < plane_diff_threshold
cur_inliers = inlier_mask.sum()
if cur_inliers > best_inliers:
best_inliers = cur_inliers
best_inliers_mask = inlier_mask
# if enough inliers
if cur_inliers.float() / points.shape[0] > 0.95:
break
if best_inliers < 3:
print('best_inliers', best_inliers)
best_plane = torch.zeros(3, dtype=torch.float, device=points.device)
else: