-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetect_eval.py
3398 lines (2605 loc) · 146 KB
/
detect_eval.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
"""
Normalized Object Coordinate Space for Category-Level 6D Object Pose and Size Estimation
Detection and evaluation
Modified based on Mask R-CNN(https://github.com/matterport/Mask_RCNN)
Written by He Wang
python3 detect_eval.py --model_type C \
--ckpt_path /home/weber/Documents/from-source/MY_NOCS/logs/modelC-train/mask_rcnn_mysynthetic_0049.h5 \
--draw \
--data corsmal \
--single_det_wireframe \
--video
"""
import os
import argparse
import cv2
import math
import ffmpeg
import random
from moviepy.editor import VideoFileClip, concatenate_videoclips, clips_array, vfx
import open3d as o3d
from open3d import *
parser = argparse.ArgumentParser()
parser.add_argument('--mode', default='detect', type=str, help="detect/eval")
parser.add_argument('--use_regression', dest='use_regression', action='store_true')
parser.add_argument('--use_delta', dest='use_delta', action='store_true')
parser.add_argument('--ckpt_path', type=str, default='logs/nocs_rcnn_res50_bin32.h5')
parser.add_argument('--model_type', type=str, default='A')
parser.add_argument('--data', type=str, help="val/real_test", default='real_test')
parser.add_argument('--gpu', default='0', type=str)
parser.add_argument('--draw', dest='draw', action='store_true', help="whether draw and save detection visualization")
parser.add_argument('--drawtag', dest='drawtag', action='store_true', help="whether draw and save detection visualization")
parser.add_argument('--num_eval', type=int, default=-1)
parser.add_argument('--subtype', type=str, help="on-table/on-table-hand/hand", default="on-table")
parser.add_argument('--image_id', type=str, help="image number in 0000 format", default="0000")
parser.add_argument('--video', action='store_true', help="run a corsmal vid")
parser.add_argument('--open3d', action='store_true', help="visualize 3d stuff via Open3D")
parser.add_argument('--separate', action='store_true', help="draw NOCS and BBox on separate images")
parser.add_argument('--CCM_eval_set', type=str, help="table/handover/action", default="table")
parser.add_argument('--quant_ccm', dest='quant_ccm', action='store_true', help="Save detections")
parser.add_argument('--quant_synccm', dest='quant_synccm', action='store_true', help="Save detections")
parser.add_argument('--single_det', dest='single_det', action='store_true', help="Detect on only one image")
parser.add_argument('--single_det_wireframe', action='store_true', help="Detect on only one image - draw wireframe before pose fitting")
parser.add_argument('--wireframe_comparison', action='store_true', help="Compare wireframes on CORSMAL videos")
parser.add_argument('--statistical', action='store_true', help="remove inliers vs. not")
parser.add_argument('--ABC_compare', action='store_true', help="Compare NOCS-A,-B & -C on CORSMAL videos")
parser.set_defaults(use_regression=False)
parser.set_defaults(draw=False)
parser.set_defaults(use_delta=False)
args = parser.parse_args()
mode = args.mode
ABC_compare = args.ABC_compare
data = args.data
ckpt_path = args.ckpt_path
use_regression = args.use_regression
use_delta = args.use_delta
num_eval = args.num_eval
drawtag = args.drawtag
quant_ccm = args.quant_ccm
quant_synccm = args.quant_synccm
single_det = args.single_det
single_det_wireframe = args.single_det_wireframe
wireframe_comparison = args.wireframe_comparison
statistical = args.statistical
model_type = args.model_type
CCM_eval_set = args.CCM_eval_set
image_id_str = args.image_id
video = args.video
os.environ['CUDA_VISIBLE_DEVICES']=args.gpu
print('Using GPU {}.'.format(args.gpu))
import sys
import datetime
import glob
import json
import time
import numpy as np
from config import Config
import utils
import model as modellib
from dataset import NOCSDataset
import _pickle as cPickle
from train import ScenesConfig
# Root directory of the project
ROOT_DIR = os.getcwd()
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Path to COCO trained weights
COCO_MODEL_PATH = os.path.join(MODEL_DIR, "mask_rcnn_coco.h5")
SYNCCM_DIR = '/media/weber/Ubuntu2/ubuntu2/synthetic'
CORSMAL_DIR = '/mnt/c7dd8318-a1d3-4622-a5fb-3fc2d8819579/CORSMAL'
class InferenceConfig(ScenesConfig):
"""Configuration for training on the toy shapes dataset.
Derives from the base Config class and overrides values specific
to the toy shapes dataset.
"""
def setNRofClasses(self,tag):
if tag == 'A' or tag == 'D':
self.NUM_CLASSES = 1 + 3
else:
self.NUM_CLASSES = 1 + 5
# Give the configuration a recognizable name
GPU_COUNT = 1
IMAGES_PER_GPU = 1
COORD_USE_REGRESSION = use_regression
if COORD_USE_REGRESSION:
COORD_REGRESS_LOSS = 'Soft_L1'
else:
COORD_NUM_BINS = 32
COORD_USE_DELTA = use_delta
USE_SYMMETRY_LOSS = True
TRAINING_AUGMENTATION = False
def quant_ccm_exp(dest_json, CCM_subset_gts_json, coco_names, synset_names, class_map, nms_flag=True, vis_flag=False, draw_tag_pls=True):
"""Runs a model on a eval subset of CCM and stores the predictions in a json file.
Arguments
----------
dest_json : str
path to store predictions in .json format
CCM_subset_gts_json: str
path to ground truths of this CCM eval subset in .json format
coco_names: array of str
coco class names
synset_names: dic
synthetic class names
class_map: dic
mapping from coco to synthetic classes
nms: boolean
perform non-max supression or not
vis_flag: boolean
visualize predictions or not
"""
print("\n\nRunning model:{}.".format(model_type))
print("\n\nDoing quantitative experiment on Corsmal Containers Manipulation subset:{}.".format(CCM_eval_set))
print("\n\n2D object detection and Dimensions estimation.\n")
config = InferenceConfig()
config.display()
coco_cls_ids = []
for coco_cls in class_map:
ind = coco_names.index(coco_cls)
coco_cls_ids.append(ind)
config.display()
###################
### SETUP MODEL ###
###################
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=config,
model_dir=MODEL_DIR)
dataset_val = NOCSDataset(synset_names, config) # init
dataset_val.load_corsmal_scenes(CCM_subset_gts_json)
dataset_val.prepare(class_map)
dataset = dataset_val
image_ids = dataset.image_ids
# Load trained weights (fill in path to trained weights here)
model_path = ckpt_path
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
# Get current time
now = datetime.datetime.now()
# Set save folder
# save_dir = os.path.join('output', "{}_{:%Y%m%dT%H%M}".format("ccm_subset", now))
# if not os.path.exists(save_dir):
# os.makedirs(save_dir)
# Set Camera Intrinsics
intrinsics = np.array([[923, 0, 640], [0., 923, 360], [0., 0., 1.]])
##################
### SETUP DATA ###
##################
PRED_JSON_P = dest_json
# Load or init json prediction file
if os.path.exists(PRED_JSON_P):
# Read json ground-truth file (contain the information about subset CCM)
with open(PRED_JSON_P) as json_file:
pred_dic = json.load(json_file)
else:
pred_dic = {}
# Read json ground-truth file (contain the information about subset CCM)
with open(CCM_subset_gts_json) as json_file:
GT_json = json.load(json_file)
##############
### DETECT ###
##############
for i, image_id in enumerate(image_ids):
print('*'*50)
print('Image {}/{}'.format(i, len(image_ids)))
# Retrieve info of current image from GT json file
im = GT_json[str(image_id)][0]
# loading RGB and DEPTH image
image = dataset.load_image(image_id)
depth = dataset.load_depth(image_id)
# DETECTION
detect_result = model.detect([image], verbose=0)
r = detect_result[0]
pred_classes = r['class_ids']
pred_masks = r['masks']
pred_coords = r['coords']
pred_bboxs = r['rois']
pred_scores = r['scores']
###### NON MAX SUPRESSION
if nms_flag:
indices2delete = nms(r['rois'], r['scores'], r['class_ids'], r['masks'], r['coords'], threshold=0.2)
pred_bboxs = np.delete(r['rois'], indices2delete, axis=0)
pred_scores = np.delete(r['scores'], indices2delete)
pred_classes = np.delete(r['class_ids'], indices2delete)
pred_masks = np.delete(r['masks'], indices2delete, axis=2)
pred_coords = np.delete(r['coords'], indices2delete, axis=2)
# Init array to save current image predictions
pred_dic[int(i)] = []
"""DIMENSION ESTIMATION WITH POSE FITTING"""
# Align NOCS predictions with depth to return 4x4 Rotation Matrices
pred_RTs, pred_scales, error_message, elapses = utils.align(pred_classes,
pred_masks,
pred_coords,
depth,
intrinsics,
synset_names,
"")
# Print error messages if any
if len(error_message):
f_log.write(error_message)
# Visualize predictions if desired
if vis_flag:
# folder to store visualisation
fol = 'result-images'
if draw_tag_pls == False:
fol = 'result-images-no-tag'
save_dir = '/home/weber/Documents/from-source/MY_NOCS/CCMs/{}/{}/'.format(CCM_eval_set, fol)
draw_ccm_detections(depth, image, save_dir, image_id, intrinsics, synset_names,
pred_bboxs, pred_classes, pred_masks, pred_coords, pred_RTs, pred_scores, pred_scales,
draw_tag=draw_tag_pls)
# Get predicted dimensions for this prediction
dimensions = get_dimensions(pred_RTs, pred_scales, pred_classes, synset_names)
"""DIMENSION ESTIMATION WITH FACE REFERENCE"""
# load the pre-trained face detection model
classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# read image
image = cv2.imread(image_path)
# perform face detection
bboxes = classifier.detectMultiScale(image)
# loop over predictions
for box in bboxes:
x, y, width, height = box
x2, y2 = x + width, y + height
# draw a rectangle over the pixels
cv2.rectangle(image, (x, y), (x2, y2), (0,0,255), 1)
# print size of 2D box
print("width:", width, "height:", height)
face_height = height
"""SAVING RESULTS"""
# Loop over predictions to save them to json file
for idx, cl in enumerate(pred_classes, start=0):
#print("Predicted class:{} | Correct class:{}".format(synset_names[cl],im['Category']))
# bbox prediction
pred_y1, pred_x1, pred_y2, pred_x2 = pred_bboxs[idx]
pred_bbox = [int(pred_x1), int(pred_y1), int(pred_x2), int(pred_y2)]
# class prediction
pred_class = synset_names[cl]
# confidence score prediction
pred_score = pred_scores[idx]
# store predictions
pred_dic[int(i)].append({
'pred_bbox': pred_bbox,
'pred_class': pred_class,
'pred_score': float(pred_score),
'pred_dimensions': dimensions[idx]
})
# Save info to .json file
with open(PRED_JSON_P, 'w') as outfile:
json.dump(pred_dic, outfile, indent=2)
def get_dimensions(pred_RTs, pred_scales, pred_classes, synset_names):
""" Aligns predictions with the depth map, and returns the prediction dimensions.
"""
pred_dimensions = []
for idx, pred_scale in enumerate(pred_scales):
# get class string
class_name = synset_names[pred_classes[idx]]
print( "Predicted class: {}".format( synset_names[pred_classes[idx]] ) )
# only align predictions for our classes
if class_name not in ["box", "non-stem", "stem"]:
dimensions = [0,0,0]
else:
# get 3d bbox
bbox3D = utils.get_3d_bbox(pred_scale)
# get 3d bbox 3d coordinates
transformed_bbox_3d = utils.transform_coordinates_3d(bbox3D, pred_RTs[idx])
#print("pred_bbox 3d points", transformed_bbox_3d.transpose()*1000)
# Get dimensions
dimensions = get_dimensions_from_3Dpoints(transformed_bbox_3d*1000)
print('Dimensions: x={:.2f}, y={:.2f}, z={:.2f}'.format(dimensions[0],dimensions[1],dimensions[2]))
#print('Dimensions: x={:.2f}, y={:.2f}, z={:.2f}'.format(dimensions[0],dimensions[1],dimensions[2]))
pred_dimensions.append(dimensions)
return pred_dimensions
def get_dimensions_from_3Dpoints(points3D, verbose=False):
"""Returns the dimensions of a 3D bounding box from its 8 points in Euclidean space.
"""
#TODO. Make it more efficient (i.e. use numpy l2 norm function)
# double number means that it is minus, e.g.: xx means minus x
xyz = points3D.transpose()[0]
xyzz = points3D.transpose()[1]
xxyz = points3D.transpose()[2]
xxyzz = points3D.transpose()[3]
xyyz = points3D.transpose()[4]
xyyzz = points3D.transpose()[5]
xxyyz = points3D.transpose()[6]
xxyyzz = points3D.transpose()[7]
# All heights (y) bot means bottom,
height1 = math.sqrt( math.pow( abs( xyyz[0] - xyz[0] ), 2) +
math.pow( abs( xyyz[1] - xyz[1] ), 2) +
math.pow( abs( xyyz[2] - xyz[2] ), 2) )
height11 = np.linalg.norm(xyyz - xyz)
print("HEIGHTS", height1, height11)
height2 = math.sqrt( math.pow( abs( xyzz[0] - xyyzz[0] ), 2) +
math.pow( abs( xyzz[1] - xyyzz[1] ), 2) +
math.pow( abs( xyzz[2] - xyyzz[2] ), 2) )
height3 = math.sqrt( math.pow( abs( xxyz[0] - xxyyz[0] ), 2) +
math.pow( abs( xxyz[1] - xxyyz[1] ), 2) +
math.pow( abs( xxyz[2] - xxyyz[2] ), 2) )
height4 = math.sqrt( math.pow( abs( xxyzz[0] - xxyyzz[0] ), 2) +
math.pow( abs( xxyzz[1] - xxyyzz[1] ), 2) +
math.pow( abs( xxyzz[2] - xxyyzz[2] ), 2) )
# All widths (x)
width1 = math.sqrt( math.pow( abs( xxyz[0] - xyz[0] ), 2) +
math.pow( abs( xxyz[1] - xyz[1] ), 2) +
math.pow( abs( xxyz[2] - xyz[2] ), 2) )
width2 = math.sqrt( math.pow( abs( xxyzz[0] - xyzz[0] ), 2) +
math.pow( abs( xxyzz[1] - xyzz[1] ), 2) +
math.pow( abs( xxyzz[2] - xyzz[2] ), 2) )
width3 = math.sqrt( math.pow( abs( xxyyz[0] - xyyz[0] ), 2) +
math.pow( abs( xxyyz[1] - xyyz[1] ), 2) +
math.pow( abs( xxyyz[2] - xyyz[2] ), 2) )
width4 = math.sqrt( math.pow( abs( xxyyzz[0] - xyyzz[0] ), 2) +
math.pow( abs( xxyyzz[1] - xyyzz[1] ), 2) +
math.pow( abs( xxyyzz[2] - xyyzz[2] ), 2) )
# All lengths (z)
length1 = math.sqrt( math.pow( abs( xyzz[0] - xyz[0] ), 2) +
math.pow( abs( xyzz[1] - xyz[1] ), 2) +
math.pow( abs( xyzz[2] - xyz[2] ), 2) )
length2 = math.sqrt( math.pow( abs( xxyzz[0] - xxyz[0] ), 2) +
math.pow( abs( xxyzz[1] - xxyz[1] ), 2) +
math.pow( abs( xxyzz[2] - xxyz[2] ), 2) )
length3 = math.sqrt( math.pow( abs( xyyzz[0] - xyyz[0] ), 2) +
math.pow( abs( xyyzz[1] - xyyz[1] ), 2) +
math.pow( abs( xyyzz[2] - xyyz[2] ), 2) )
length4 = math.sqrt( math.pow( abs( xxyyzz[0] - xxyyz[0] ), 2) +
math.pow( abs( xxyyzz[1] - xxyyz[1] ), 2) +
math.pow( abs( xxyyzz[2] - xxyyz[2] ), 2) )
if verbose:
print("3D points:")
print('( x, y, z) : {}'.format(points3D.transpose()[0]))
print('( x, y,-z) : {}'.format(points3D.transpose()[1]))
print('(-x, y, z) : {}'.format(points3D.transpose()[2]))
print('(-x, y,-z) : {}'.format(points3D.transpose()[3]))
print('( x,-y, z) : {}'.format(points3D.transpose()[4]))
print('( x,-y,-z) : {}'.format(points3D.transpose()[5]))
print('(-x,-y, z) : {}'.format(points3D.transpose()[6]))
print('(-x,-y,-z) : {}'.format(points3D.transpose()[7]))
print("heights: {:.2f} | {:.2f} | {:.2f} | {:.2f}".format(height1,
height2,
height3,
height4))
print("widths: {:.2f} | {:.2f} | {:.2f} | {:.2f}".format(width1,
width2,
width3,
width4))
print("lengths: {:.2f} | {:.2f} | {:.2f} | {:.2f}".format(length1,
length2,
length3,
length4))
return width1, height1, length1
def nms(bounding_boxes, confidence_scores, classIDs, maskz, coordz, threshold):
# If no bounding boxes, return empty list
if len(bounding_boxes) == 0:
return [], []
# Bounding boxes
boxes = np.array(bounding_boxes)
# coordinates of bounding boxes
start_y = boxes[:, 0]
start_x = boxes[:, 1]
end_y = boxes[:, 2]
end_x = boxes[:, 3]
# Confidence scores of bounding boxes
score = np.array(confidence_scores)
# Picked bounding boxes
picked_indices = []
# Compute areas of bounding boxes
areas = (end_x - start_x + 1) * (end_y - start_y + 1)
# Sort by confidence score of bounding boxes
order = np.argsort(score)
# Iterate bounding boxes
while order.size > 0:
# The index of largest confidence score
index = order[-1]
# Pick the bounding box with largest confidence score
picked_indices.append(index)
# Compute ordinates of intersection-over-union(IOU)
x1 = np.maximum(start_x[index], start_x[order[:-1]])
x2 = np.minimum(end_x[index], end_x[order[:-1]])
y1 = np.maximum(start_y[index], start_y[order[:-1]])
y2 = np.minimum(end_y[index], end_y[order[:-1]])
# Compute areas of intersection-over-union
w = np.maximum(0.0, x2 - x1 + 1)
h = np.maximum(0.0, y2 - y1 + 1)
intersection = w * h
# Compute the ratio between intersection and union
ratio = intersection / (areas[index] + areas[order[:-1]] - intersection)
left = np.where(ratio < threshold)
order = order[left]
allindices = np.arange(0,len(classIDs))
indices2delete = np.setdiff1d(allindices,picked_indices)
print('allindices: {} | indices2keep: {} | indices2delete: {}'.format(allindices, picked_indices, indices2delete))
return indices2delete
def detect_and_display(coco_names, synset_names, class_map):
config = InferenceConfig()
config.display()
# dataset directories
coco_dir = os.path.join('data', 'coco')
synccm_dir = "/media/weber/Ubuntu2/ubuntu2/synthetic"
corsmal_dir = "/mnt/c7dd8318-a1d3-4622-a5fb-3fc2d8819579/CORSMAL/"
coco_cls_ids = []
for coco_cls in class_map:
ind = coco_names.index(coco_cls)
coco_cls_ids.append(ind)
config.display()
assert mode in ['detect', 'eval']
if mode == 'detect':
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=config,
model_dir=MODEL_DIR)
gt_dir = os.path.join('data','gts', data)
if data == 'val':
dataset_val = NOCSDataset(synset_names, config) # init
dataset_val.load_synccm_scenes(synccm_dir, ["on-table"], ["val"], False)
dataset_val.prepare(class_map)
dataset = dataset_val
elif data == 'train':
dataset_train = NOCSDataset(synset_names, args.subtype, 'train', config) # init
dataset_train.load_synccm_scenes(synccm_dir, False)
dataset_train.prepare(class_map)
dataset = dataset_train
elif data == 'test':
dataset_test = NOCSDataset(synset_names, args.subtype, 'test', config) # init
dataset_test.load_synccm_scenes(synccm_dir, False)
dataset_test.prepare(class_map)
dataset = dataset_test
elif data == 'corsmal':
dataset_corsmal_test = NOCSDataset(synset_names, config)
#dataset_corsmal_test.load_corsmal_scenes()
dataset_corsmal_test.load_corsmal_vid()
dataset_corsmal_test.prepare(class_map)
dataset = dataset_corsmal_test
else:
assert False, "Unknown data resource."
# Load trained weights (fill in path to trained weights here)
model_path = ckpt_path
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, mode='inference', by_name=True)
image_ids = dataset.image_ids
save_per_images = 10
# Get current time
now = datetime.datetime.now()
# Set save folder
save_dir = os.path.join('output', "{}_{:%Y%m%dT%H%M}".format(data, now))
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# Set logger
log_file = os.path.join(save_dir, 'error_log.txt')
f_log = open(log_file, 'w')
# Set Camera Intrinsics
intrinsics = np.array([[923, 0, 640], [0., 923, 360], [0., 0., 1.]])
# Init elapsed times
elapse_times = []
# Let's DETECT
if mode != 'eval':
for i, image_id in enumerate(image_ids):
print('*'*50)
image_start = time.time()
print('Image id: ', image_id)
image_path = dataset.image_info[image_id]["rgb_path"]
print(image_path)
# record results
result = {}
# loading RGB and DEPTH image
image = dataset.load_image(image_id)
depth = dataset.load_depth(image_id)
# load LABELS for synthetic data
if data in ['train', 'test', 'val']:
gt_mask, gt_coord, gt_class_ids, gt_domain_label = dataset.load_mask(image_id) #gt_scales
gt_bbox = utils.extract_bboxes(gt_mask)
result['gt_class_ids'] = gt_class_ids
result['gt_bboxes'] = gt_bbox
result['gt_RTs'] = None
#TODO: load scales from .txt file
result['gt_scales'] = None
# no LABELS for corsmal data
else:
gt_mask, gt_coord, gt_class_ids, gt_domain_label = None, None, None, None
gt_bbox = None
result['gt_RTs'] = None
gt_scales = None
result['image_id'] = image_id
result['image_path'] = image_path
image_path_parsing = image_path.split('/')
# Align gt coord with depth to get RT, only applicable to synthetic data
if data in ['train', 'test', 'val']: # x: i put train and val in here to not predict ground truths YET
if len(gt_class_ids) == 0:
print('No gt instance exists in this image.')
print('\nAligning ground truth...')
start = time.time()
result['gt_RTs'], gt_scales, error_message, _ = utils.align(gt_class_ids,
gt_mask,
gt_coord,
depth,
intrinsics,
synset_names,
image_path)
#save_dir+'/'+'{}_{}_{}_{}_gt_'.format(image_path_parsing[-4], data, image_path_parsing[-2], image_path_parsing[-1]))
print('New alignment takes {:03f}s.'.format(time.time() - start))
result['gt_scales'] = gt_scales
if len(error_message):
f_log.write(error_message)
###### DETECTION
start = time.time()
detect_result = model.detect([image], verbose=0)
r = detect_result[0]
elapsed = time.time() - start
print('\nDetection takes {:03f}s.'.format(elapsed))
result['pred_class_ids'] = r['class_ids']
result['pred_bboxes'] = r['rois']
result['pred_RTs'] = None
result['pred_scores'] = r['scores']
###### NON MAX SUPRESSION
indices2delete = nms(r['rois'], r['scores'], r['class_ids'], r['masks'], r['coords'], threshold=0.2)
# print(result['pred_bboxes'].shape)
# print(result['pred_scores'].shape)
# print(result['pred_class_ids'].shape)
# print(r['masks'].shape)
# print(r['coords'].shape)
kept_bboxes = np.delete(result['pred_bboxes'], indices2delete, axis=0)
kept_scores = np.delete(result['pred_scores'], indices2delete)
kept_classes = np.delete(result['pred_class_ids'], indices2delete)
kept_masks = np.delete(r['masks'], indices2delete, axis=2)
kept_coords = np.delete(r['coords'], indices2delete, axis=2)
# print("\nResult:\n")
# print(kept_bboxes.shape)
# print(kept_scores.shape)
# print(kept_classes.shape)
# print(kept_masks.shape)
# print(kept_coords.shape)
if len(r['class_ids']) == 0:
print('No instance is detected.')
print('Aligning predictions...')
start = time.time()
result['pred_RTs'], result['pred_scales'], error_message, elapses = utils.align(kept_classes,
kept_masks,
kept_coords,
depth,
intrinsics,
synset_names,
image_path)
#save_dir+'/'+'{}_{}_{}_pred_'.format(data, image_path_parsing[-2], image_path_parsing[-1]))
print('New alignment takes {:03f}s.'.format(time.time() - start))
elapse_times += elapses
if len(error_message):
f_log.write(error_message)
print("PRED_SCALES=", result['pred_scales'])
if args.draw:
draw_ground_truth = True if data != "corsmal" else False
utils.draw_detections(depth, image, save_dir, data, image_path_parsing[-2]+'_'+image_path_parsing[-1], intrinsics, synset_names, False,
gt_bbox, gt_class_ids, gt_mask, gt_coord, result['gt_RTs'], gt_scales, None,
kept_bboxes, kept_classes, kept_masks, kept_coords, result['pred_RTs'], kept_scores, result['pred_scales'], draw_gt=draw_ground_truth, draw_tag=drawtag)
path_parse = image_path.split('/')
image_short_path = '_'.join(path_parse[-3:])
save_path = os.path.join(save_dir, 'results_{}_{}.pkl'.format(image_path_parsing[-4], image_short_path))
with open(save_path, 'wb') as f:
cPickle.dump(result, f)
print('Results of image {} has been saved to {}.'.format(image_short_path, save_path))
elapsed = time.time() - image_start
print('Takes {} to finish this image.'.format(elapsed))
print('Alignment average time: ', np.mean(np.array(elapse_times)))
print('\n')
f_log.close()
else: # mode == eval
log_dir = 'output/'
#Xavier:
log_dir = "/home/weber/Documents/from-source/MY_NOCS/output/val_20201204T1153 "
result_pkl_list = glob.glob(os.path.join(log_dir, 'results_*.pkl'))
result_pkl_list = sorted(result_pkl_list)[:num_eval]
assert len(result_pkl_list)
final_results = []
for pkl_path in result_pkl_list:
with open(pkl_path, 'rb') as f:
result = cPickle.load(f)
# if not 'gt_handle_visibility' in result:
# result['gt_handle_visibility'] = np.ones_like(result['gt_class_ids'])
# print('can\'t find gt_handle_visibility in the pkl.')
# else:
# assert len(result['gt_handle_visibility']) == len(result['gt_class_ids']), "{} {}".format(result['gt_handle_visibility'], result['gt_class_ids'])
if type(result) is list:
final_results += result
elif type(result) is dict:
final_results.append(result)
else:
assert False
aps = utils.compute_degree_cm_mAP(final_results, synset_names, log_dir,
degree_thresholds = [5, 10, 15],#range(0, 61, 1),
shift_thresholds= [5, 10, 15], #np.linspace(0, 1, 31)*15,
iou_3d_thresholds=np.linspace(0, 1, 101),
iou_pose_thres=0.1,
use_matches_for_pose=True)
def draw_ccm_detections(depth, image, save_dir, image_id, intrinsics, synset_names,
pred_bbox, pred_class_ids, pred_mask, pred_coord, pred_RTs, pred_scores, pred_scales,
draw_tag=True, human_chair_segm_flag=True):
alpha = 0.5
############
### NOCS ###
############
# path to store NOCS coord predictions
output_path = os.path.join(save_dir, '{}_{}_coord.png'.format(image_id, model_type))
# copy rgb image, we will draw on this
draw_image = image.copy()
# Get number of predictions
num_pred_instances = len(pred_class_ids)
# Loop over predictions
for i in range(num_pred_instances):
# Get predicted class
cls_id = pred_class_ids[i]
# don't draw person or chair
if cls_id == 4 or cls_id == 5:
if human_chair_segm_flag == False:
continue
else:
mask = pred_mask[:, :, i]
cind, rind = np.where(mask == 1)
if cls_id == 4: # draw red mask for person
draw_image[cind, rind] = [255,0,0]
else: # draw blue mask for chair
draw_image[cind, rind] = [0,255,0]
else:
mask = pred_mask[:, :, i]
cind, rind = np.where(mask == 1)
coord_data = pred_coord[:, :, i, :].copy()
draw_image[cind, rind] = coord_data[cind, rind] * 255
# Draw class and confidence?
if draw_tag:
for i in range(num_pred_instances):
cls_id = pred_class_ids[i]
# don't draw person or chair
if human_chair_segm_flag == False and (cls_id == 4 or cls_id == 5):
continue
overlay = draw_image.copy()
text = synset_names[pred_class_ids[i]]+'({:.2f})'.format(pred_scores[i]) #og
overlay = utils.draw_text(overlay, pred_bbox[i], text, draw_box=True)
cv2.addWeighted(overlay, alpha, draw_image, 1 - alpha, 0, draw_image)
# Save NOCS result image
cv2.imwrite(output_path, draw_image[:, :, ::-1])
############
### BBOX ###
############
# Set output path and copy rgb image
output_path = os.path.join(save_dir, '{}_{}_bbox.png'.format(image_id, model_type))
draw_image_bbox = image.copy()
# Loop over predictions
for ind in range(num_pred_instances):
# get predicted class and rotation matrix (RT)
RT = pred_RTs[ind]
cls_id = pred_class_ids[ind]
# don't draw person or chair
if human_chair_segm_flag == False and (cls_id == 4 or cls_id == 5):
continue
### DRAW THE 3 ROTATIONAL AXES
xyz_axis = 0.3*np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]]).transpose()
transformed_axes = utils.transform_coordinates_3d(xyz_axis, RT)
projected_axes = utils.calculate_2d_projections(transformed_axes, intrinsics)
### DRAW THE BOUNDING BOX
bbox_3d = utils.get_3d_bbox(pred_scales[ind, :], 0)
transformed_bbox_3d = utils.transform_coordinates_3d(bbox_3d, RT)
projected_bbox = utils.calculate_2d_projections(transformed_bbox_3d, intrinsics)
draw_image_bbox = utils.draw(draw_image_bbox, projected_bbox, projected_axes, (255, 0, 0))
### DRAW THE DIMENSIONS X, Y, Z (TEXT)
if draw_tag:
xx,yy,zz = get_dimensions_from_3Dpoints(transformed_bbox_3d*1000)
overlay = draw_image_bbox.copy()
text = 'Dim:{:.1f},{:.1f}, {:.1f})'.format(xx,yy,zz)
overlay = utils.draw_text(overlay, pred_bbox[ind], text)
cv2.addWeighted(overlay, alpha, draw_image_bbox, 1 - alpha, 0, draw_image_bbox)
# Save result
cv2.imwrite(output_path, draw_image_bbox[:, :, ::-1])
def quant_synccm_exp(coco_names, synset_names, class_map, nms_flag=True, vis_flag=False):
"""Runs a model on a subset of SynCCM and stores the predictions in a json file.
Arguments
----------
coco_names: array of str
coco class names
synset_names: dic
synthetic class names
class_map: dic
mapping from coco to synthetic classes
nms: boolean
perform non-max supression or not
vis_flag: boolean
visualize predictions or not
"""
config = InferenceConfig()
config.display()
coco_cls_ids = []
for coco_cls in class_map:
ind = coco_names.index(coco_cls)
coco_cls_ids.append(ind)
config.display()
###################
### SETUP MODEL ###
###################
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=config,
model_dir=MODEL_DIR)
dataset_val = NOCSDataset(synset_names, config) # init
dataset_val.load_synccm_scenes(SYNCCM_DIR, ["hand"], ["train"], if_calculate_mean=False)
dataset_val.prepare(class_map)
dataset = dataset_val
# Load trained weights (fill in path to trained weights here)
model_path = ckpt_path
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
image_ids = dataset.image_ids
# Get current time
now = datetime.datetime.now()
# Set save folder
# save_dir = os.path.join('output', "{}_{:%Y%m%dT%H%M}".format("ccm_subset", now))
# if not os.path.exists(save_dir):
# os.makedirs(save_dir)
# Set Camera Intrinsics
intrinsics = np.array([[923, 0, 640], [0., 923, 360], [0., 0., 1.]])
##############
### DETECT ###
##############
for i, image_id in enumerate(image_ids):
print('*'*50)
print('Image {}/{}'.format(i, len(image_ids)))
# loading RGB and DEPTH image
image = dataset.load_image(image_id)
depth = dataset.load_depth(image_id)
# DETECTION
detect_result = model.detect([image], verbose=0)
r = detect_result[0]
pred_classes = r['class_ids']
pred_masks = r['masks']
pred_coords = r['coords']
pred_bboxs = r['rois']
pred_scores = r['scores']
###### NON MAX SUPRESSION
if nms_flag:
indices2delete = nms(r['rois'], r['scores'], r['class_ids'], r['masks'], r['coords'], threshold=0.2)
# print(result['pred_bboxes'].shape, result['pred_scores'].shape, result['pred_class_ids'].shape, r['masks'].shape, r['coords'].shape)
pred_bboxs = np.delete(r['rois'], indices2delete, axis=0)
pred_scores = np.delete(r['scores'], indices2delete)
pred_classes = np.delete(r['class_ids'], indices2delete)
pred_masks = np.delete(r['masks'], indices2delete, axis=2)
pred_coords = np.delete(r['coords'], indices2delete, axis=2)