-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
2300 lines (1831 loc) · 89.4 KB
/
dataset.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
# MIT License
# Copyright (c) 2022 Alessio
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##############################################################################
import os
import sys
import datetime
import time
import glob
import json
import numpy as np
from numpy import random
from skimage import exposure
import cv2
from config import Config
import utils
sys.path.append('./cocoapi/PythonAPI')
from pycocotools.coco import COCO
coco_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
class NocsClasses():
def __init__(self):
self.coco_names = coco_names
self.synset_names = ['BG', #0
'bottle', #1
'bowl', #2
'camera', #3
'can', #4
'laptop',#5
'mug'#6
]
self.class_map = class_map = {
'bottle': 'bottle',
'bowl':'bowl',
'cup':'mug',
'laptop': 'laptop',
}
self.coco_cls_ids = []
self.SetMappedCocoClasses()
def SetMappedCocoClasses(self):
for coco_cls in self.class_map:
ind = self.coco_names.index(coco_cls)
self.coco_cls_ids.append(ind)
def GetMappedCocoClasses(self):
return self.coco_cls_ids
class ChocClasses():
def __init__(self):
self.coco_names = coco_names
self.synset_names = ['BG', #0
'box', #1 gray-lvl:50
'non-stem', #2 gray-lvl:100
'stem', #3 gray-lvl:150
'person' #4
# 'chair' #5
] # hand gray-lvl:200
self.class_map = {
'cup':'non-stem',
'wine glass': 'stem',
'person':'person'
# 'person':'person',
# 'chair': 'chair'
}
self.coco_cls_ids = []
self.SetMappedCocoClasses()
def SetMappedCocoClasses(self):
for coco_cls in self.class_map:
ind = self.coco_names.index(coco_cls)
self.coco_cls_ids.append(ind)
def GetMappedCocoClasses(self):
return self.coco_cls_ids
############################################################
# Dataset
############################################################
class Dataset(object):
"""The base class for dataset classes.
To use it, create a new class that adds functions specific to the dataset
you want to use. For example:
class CatsAndDogsDataset(Dataset):
def load_cats_and_dogs(self):
...
def load_mask(self, image_id):
...
def image_reference(self, image_id):
...
See COCODataset and ShapesDataset as examples.
"""
def __init__(self, class_map=None):
self._image_ids = []
self.image_info = []
# Background is always the first class
self.class_info = [{"source": "", "id": 0, "name": "BG"}]
self.source_class_ids = {}
def add_class(self, source, class_id, class_name):
assert "." not in source, "Source name cannot contain a dot"
# Does the class exist already?
for info in self.class_info:
if info['source'] == source and info["id"] == class_id:
# source.class_id combination already available, skip
return
# Add the class
self.class_info.append({
"source": source,
"id": class_id,
"name": class_name,
})
def add_image(self, source, image_id, path, **kwargs):
image_info = {
"id": image_id,
"source": source,
"path": path,
}
image_info.update(kwargs)
self.image_info.append(image_info)
def image_reference(self, image_id):
"""Return a link to the image in its source Website or details about
the image that help looking it up or debugging it.
Override for your dataset, but pass to this function
if you encounter images not in your dataset.
"""
return ""
def prepare(self, class_map=None):
"""Prepares the Dataset class for use.
"""
def clean_name(name):
"""Returns a shorter version of object names for cleaner display."""
return ",".join(name.split(",")[:1])
# Build (or rebuild) everything else from the info dicts.
#self.num_classes = len(self.class_info)
self.num_classes = 0
#self.class_ids = np.arange(self.num_classes)
self.class_ids = []
#self.class_names = [clean_name(c["name"]) for c in self.class_info]
self.class_names = []
#self.class_from_source_map = {"{}.{}".format(info['source'], info['id']): id
# for info, id in zip(self.class_info, self.class_ids)}
self.class_from_source_map = {}
for cls_info in self.class_info:
print("CLS_INFO:", cls_info)
source = cls_info["source"]
if source == 'coco':
map_key = "{}.{}".format(cls_info['source'], cls_info['id'])
print("map_key:", map_key)
print("cls_info['name']", cls_info["name"])
print("class_map[cls_info['name']]", class_map[cls_info["name"]])
self.class_from_source_map[map_key] = self.class_names.index(class_map[cls_info["name"]])
else:
self.class_ids.append(self.num_classes)
self.num_classes += 1
self.class_names.append(cls_info["name"])
map_key = "{}.{}".format(cls_info['source'], cls_info['id'])
print("map_key:", map_key)
print("cls_info['source']", cls_info['source'])
print("cls_info['id']", cls_info['id'])
self.class_from_source_map[map_key] = self.class_ids[-1]
self.num_images = len(self.image_info)
self._image_ids = np.arange(self.num_images)
# Mapping from source class and image IDs to internal IDs
self.image_from_source_map = {"{}.{}".format(info['source'], info['id']): id
for info, id in zip(self.image_info, self.image_ids)}
# Map sources to class_ids they support
self.sources = list(set([i['source'] for i in self.class_info]))
'''
self.source_class_ids = {}
# Loop over datasets
for source in self.sources:
self.source_class_ids[source] = []
# Find classes that belong to this dataset
for i, info in enumerate(self.class_info):
# Include BG class in all datasets
if i == 0 or source == info['source']:
self.source_class_ids[source].append(i)
'''
print(self.class_names)
print(self.class_from_source_map)
print(self.sources)
#print(self.source_class_ids)
def map_source_class_id(self, source_class_id):
"""Takes a source class ID and returns the int class ID assigned to it.
For example:
dataset.map_source_class_id("coco.12") -> 23
"""
if source_class_id in self.class_from_source_map:
return self.class_from_source_map[source_class_id]
else:
return None
def get_source_class_id(self, class_id, source):
"""Map an internal class ID to the corresponding class ID in the source dataset."""
info = self.class_info[class_id]
assert info['source'] == source
return info['id']
def append_data(self, class_info, image_info):
self.external_to_class_id = {}
for i, c in enumerate(self.class_info):
for ds, id in c["map"]:
self.external_to_class_id[ds + str(id)] = i
# Map external image IDs to internal ones.
self.external_to_image_id = {}
for i, info in enumerate(self.image_info):
self.external_to_image_id[info["ds"] + str(info["id"])] = i
@property
def image_ids(self):
return self._image_ids
def source_image_link(self, image_id):
"""Returns the path or URL to the image.
Override this to return a URL to the image if it's availble online for easy
debugging.
"""
return self.image_info[image_id]["path"]
def load_image(self, image_id):
"""Load the specified image and return a [H,W,3] Numpy array.
"""
# Load image
image = scipy.misc.imread(self.image_info[image_id]['path'])
# If grayscale. Convert to RGB for consistency.
if image.ndim != 3:
image = skimage.color.gray2rgb(image)
return image
def load_mask(self, image_id):
"""Load instance masks for the given image.
Different datasets use different ways to store masks. Override this
method to load instance masks and return them in the form of am
array of binary masks of shape [height, width, instances].
Returns:
masks: A bool array of shape [height, width, instance count] with
a binary mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# Override this function to load a mask from your dataset.
# Otherwise, it returns an empty mask.
mask = np.empty([0, 0, 0])
class_ids = np.empty([0], np.int32)
return mask, class_ids
def resize_image(image, min_dim=None, max_dim=None, padding=False):
"""
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 = scipy.misc.imresize(
image, (round(h * scale), round(w * scale)))
# Need padding?
if padding:
# Get new height and width
h, w = image.shape[:2]
top_pad = (max_dim - h) // 2
bottom_pad = max_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, the mask, and the coordinate map 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]
# for instance mask
if len(mask.shape) == 3:
mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0)
new_padding = padding
# for coordinate map
elif len(mask.shape) == 4:
mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1, 1], order=0)
new_padding = padding + [(0, 0)]
else:
assert False
mask = np.pad(mask, new_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.
"""
# for instance mask
if len(mask.shape)==3:
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]*255
m = scipy.misc.imresize(m.astype(np.uint8), mini_shape, interp='nearest')
mini_mask[:, :, i] = np.where(m >= 128, 1, 0)
# for coordinate map
elif len(mask.shape)==4:
assert mask.shape[-1] == 3 ## coordinate map
mini_mask = np.zeros(mini_shape + mask.shape[-2:], dtype=np.float32)
for i in range(mask.shape[-2]):
m = mask[:, :, i, :]
y1, x1, y2, x2 = bbox[i][:4]
m = m[y1:y2, x1:x2, :]*255
m = scipy.misc.imresize(m.astype(np.uint8), mini_shape+(mask.shape[-1],), interp='nearest')
mini_mask[:, :, i, :] = m.astype(float)/255
else:
assert False
return mini_mask
def expand_mask(bbox, mini_mask, image_shape):
"""Resizes mini masks back to image size. Reverses the change
of minimize_mask().
See inspect_data.ipynb notebook for more details.
"""
# for instance mask
if len(mini_mask.shape) == 3:
mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
for i in range(mask.shape[-1]):
m = mini_mask[:, :, i]
y1, x1, y2, x2 = bbox[i][:4]
h = y2 - y1
w = x2 - x1
m = scipy.misc.imresize(m.astype(float), (h, w), interp='bilinear')
mask[y1:y2, x1:x2, i] = np.where(m >= 128, 1, 0)
elif len(mini_mask.shape) == 4:
assert mini_mask.shape[-1] == 3 ## coordinate map
mask = np.zeros(image_shape[:2] + mini_mask.shape[-2:], dtype=np.float32)
for i in range(mask.shape[-2]):
m = mini_mask[:, :, i, :]
y1, x1, y2, x2 = bbox[i][:4]
h = y2 - y1
w = x2 - x1
m = scipy.misc.imresize(m.astype(float), (h, w, mini_mask.shape[-1]), interp='nearest')
mask[y1:y2, x1:x2, i, :] = m
return mask
# TODO: Build and use this function to reduce code duplication
def mold_mask(mask, config):
pass
def unmold_mask(mask, bbox, image_shape):
"""Converts a mask generated by the neural network into a format similar
to it's original shape.
mask: [height, width] of type float. A small, typically 28x28 mask.
bbox: [y1, x1, y2, x2]. The box to fit the mask in.
Returns a binary mask with the same size as the original image.
"""
threshold = 0.5
y1, x1, y2, x2 = bbox
mask = scipy.misc.imresize(
mask, (y2 - y1, x2 - x1), interp='bilinear').astype(np.float32) / 255.0
mask = np.where(mask >= threshold, 1, 0).astype(np.uint8)
# Put the mask in the right location.
full_mask = np.zeros(image_shape[:2], dtype=np.uint8)
full_mask[y1:y2, x1:x2] = mask
return full_mask
def unmold_coord(coord, bbox, image_shape):
"""Converts a mask generated by the neural network into a format similar
to it's original shape.
coord: [height, width, 3] of type float. A small, typically 28x28 mask.
bbox: [y1, x1, y2, x2]. The box to fit the mask in.
Returns a coordinate map with the same size as the original image.
"""
y1, x1, y2, x2 = bbox
#max_coord_x = np.amax(coord[:, :, 0])
#max_coord_y = np.amax(coord[:, :, 1])
#max_coord_z = np.amax(coord[:, :, 2])
#print('before resize:')
#print(max_coord_x, max_coord_y, max_coord_z)
#coord = scipy.misc.imresize(
# coord, (y2 - y1, x2 - x1, 3), interp='nearest').astype(np.float32)/ 255.0
# #coord, (y2 - y1, x2 - x1, 3), interp='bilinear').astype(np.uint8)
coord = cv2.resize(coord, (x2 - x1, y2 - y1), interpolation=cv2.INTER_LINEAR)
#max_coord_x_resize = np.amax(coord[:, :, 0])
#max_coord_y_resize = np.amax(coord[:, :, 1])
#max_coord_z_resize = np.amax(coord[:, :, 2])
#print('after resize:')
#print(max_coord_x_resize, max_coord_y_resize, max_coord_z_resize)
# Put the mask in the right location.
full_coord= np.zeros(image_shape, dtype=np.float32)
full_coord[y1:y2, x1:x2, :] = coord
return full_coord
## for COCO
def annToRLE(ann, height, width):
"""
Convert annotation which can be polygons, uncompressed RLE to RLE.
:return: binary mask (numpy 2D array)
"""
segm = ann['segmentation']
if isinstance(segm, list):
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = maskUtils.frPyObjects(segm, height, width)
rle = maskUtils.merge(rles)
elif isinstance(segm['counts'], list):
# uncompressed RLE
rle = maskUtils.frPyObjects(segm, height, width)
else:
# rle
rle = ann['segmentation']
return rle
def annToMask(ann, height, width):
"""
Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
:return: binary mask (numpy 2D array)
"""
rle = annToRLE(ann, height, width)
m = maskUtils.decode(rle)
return m
##############################################################################
##############################################################################
############################ NOCS DATASET ####################################
##############################################################################
##############################################################################
class NOCSDataset(Dataset):
"""Generates the NOCS dataset.
"""
def __init__(self, synset_names, subset, config=Config()):
self._image_ids = []
self.image_info = []
# Background is always the first class
self.class_info = [{"source": "", "id": 0, "name": "BG"}]
self.source_class_ids = {}
# which dataset: train/val/test
self.subset = subset
assert subset in ['train', 'val', 'test', 'corsmal']
self.config = config
self.source_image_ids = {}
# Add classes
for i, obj_name in enumerate(synset_names):
if i == 0: ## class 0 is bg class
continue
self.add_class("BG", i, obj_name) ## class id starts with 1
def load_camera_scenes(self, dataset_dir, if_calculate_mean=False):
"""Load a subset of the CAMERA dataset.
dataset_dir: The root directory of the CAMERA dataset.
subset: What to load (train, val)
if_calculate_mean: if calculate the mean color of the images in this dataset
"""
image_dir = os.path.join(dataset_dir, self.subset)
source = "CAMERA"
num_images_before_load = len(self.image_info)
folder_list = [name for name in os.listdir(image_dir) if os.path.isdir(os.path.join(image_dir, name))]
num_total_folders = len(folder_list)
image_ids = range(10*num_total_folders)
color_mean = np.zeros((0, 3), dtype=np.float32)
# Add images
for i in image_ids:
print('Progress loading CAMERA scenes:' , '[{}/{}]'.format(i, len(image_ids)), end='\r')
image_id = int(i) % 10
folder_id = int(i) // 10
image_path = os.path.join(image_dir, '{:05d}'.format(folder_id), '{:04d}'.format(image_id))
color_path = image_path + '_color.png'
if not os.path.exists(color_path):
continue
meta_path = os.path.join(image_dir, '{:05d}'.format(folder_id), '{:04d}_meta.txt'.format(image_id))
inst_dict = {}
with open(meta_path, 'r') as f:
for line in f:
line_info = line.split(' ')
inst_id = int(line_info[0]) ##one-indexed
cls_id = int(line_info[1]) ##zero-indexed
# skip background objs
# symmetry_id = int(line_info[2])
inst_dict[inst_id] = cls_id
width = self.config.IMAGE_MAX_DIM # meta_data['viewport_size_x'].flatten()[0]
height = self.config.IMAGE_MIN_DIM # meta_data['viewport_size_y'].flatten()[0]
self.add_image(
source=source,
image_id=image_id,
path=image_path,
width=width,
height=height,
inst_dict=inst_dict)
if if_calculate_mean:
image_file = image_path + '_color.png'
image = cv2.imread(image_file).astype(np.float32)
print(i)
color_mean_image = np.mean(image, axis=(0, 1))[:3]
color_mean_image = np.expand_dims(color_mean_image, axis=0)
color_mean = np.append(color_mean, color_mean_image, axis=0)
if if_calculate_mean:
dataset_color_mean = np.mean(color_mean[::-1], axis=0)
print('The mean color of this dataset is ', dataset_color_mean)
num_images_after_load = len(self.image_info)
self.source_image_ids[source] = np.arange(num_images_before_load, num_images_after_load)
print('{} images are loaded into the dataset from {}.'.format(num_images_after_load - num_images_before_load, source))
def load_real_scenes(self, dataset_dir):
"""Load a subset of the Real dataset.
dataset_dir: The root directory of the Real dataset.
subset: What to load (train, val, test)
if_calculate_mean: if calculate the mean color of the images in this dataset
"""
source = "Real"
num_images_before_load = len(self.image_info)
folder_name = 'train' if self.subset == 'train' else 'test'
image_dir = os.path.join(dataset_dir, folder_name)
folder_list = [name for name in glob.glob(image_dir + '/*') if os.path.isdir(name)]
folder_list = sorted(folder_list)
image_id = 0
for folder in folder_list:
image_list = glob.glob(os.path.join(folder, '*_color.png'))
image_list = sorted(image_list)
for image_full_path in image_list:
image_name = os.path.basename(image_full_path)
image_ind = image_name.split('_')[0]
image_path = os.path.join(folder, image_ind)
meta_path = image_path + '_meta.txt'
inst_dict = {}
with open(meta_path, 'r') as f:
for line in f:
line_info = line.split(' ')
inst_id = int(line_info[0]) ##one-indexed
cls_id = int(line_info[1]) ##zero-indexed
# symmetry_id = int(line_info[2])
inst_dict[inst_id] = cls_id
width = self.config.IMAGE_MAX_DIM # meta_data['viewport_size_x'].flatten()[0]
height = self.config.IMAGE_MIN_DIM # meta_data['viewport_size_y'].flatten()[0]
self.add_image(
source=source,
image_id=image_id,
path=image_path,
width=width,
height=height,
inst_dict=inst_dict)
image_id += 1
num_images_after_load = len(self.image_info)
self.source_image_ids[source] = np.arange(num_images_before_load, num_images_after_load)
print('{} images are loaded into the dataset from {}.'.format(num_images_after_load - num_images_before_load, source))
def load_coco(self, dataset_dir, subset, class_names):
"""Load a subset of the COCO dataset.
dataset_dir: The root directory of the COCO dataset.
subset: What to load (train, val, minival, val35k)
class_ids: If provided, only loads images that have the given classes.
"""
source = "coco"
num_images_before_load = len(self.image_info)
image_dir = os.path.join(dataset_dir, "images", "train2017" if subset == "train"
else "val2017")
# Create COCO object
json_path_dict = {
"train": "annotations/instances_train2017.json",
"val": "annotations/instances_val2017.json",
}
coco = COCO(os.path.join(dataset_dir, json_path_dict[subset]))
# Load all classes or a subset?
image_ids = set()
class_ids = coco.getCatIds(catNms=class_names)
for cls_name in class_names:
catIds = coco.getCatIds(catNms=[cls_name])
imgIds = coco.getImgIds(catIds=catIds )
image_ids = image_ids.union(set(imgIds))
image_ids = list(set(image_ids))
# Add classes
for cls_id in class_ids:
self.add_class("coco", cls_id, coco.loadCats(cls_id)[0]["name"])
print('Add coco class: '+coco.loadCats(cls_id)[0]["name"])
# Add images
num_existing_images = len(self.image_info)
for i, image_id in enumerate(image_ids):
self.add_image(
source=source,
image_id=i + num_existing_images,
path=os.path.join(image_dir, coco.imgs[image_id]['file_name']),
width=coco.imgs[image_id]["width"],
height=coco.imgs[image_id]["height"],
annotations=coco.loadAnns(coco.getAnnIds(imgIds=[image_id], iscrowd=False)))
num_images_after_load = len(self.image_info)
self.source_image_ids[source] = np.arange(num_images_before_load, num_images_after_load)
print('{} images are loaded into the dataset from {}.'.format(num_images_after_load - num_images_before_load, source))
def load_image(self, image_id):
"""Generate an image from the specs of the given image ID.
Typically this function loads the image from a file.
"""
info = self.image_info[image_id]
if info["source"] in ["CAMERA", "Real"]:
image_path = info["path"] + '_color.png'
assert os.path.exists(image_path), "{} is missing".format(image_path)
#depth_path = info["path"] + '_depth.png'
elif info["source"]=='coco':
image_path = info["path"]
else:
assert False, "[ Error ]: Unknown image source: {}".format(info["source"])
#print(image_path)
image = cv2.imread(image_path)[:, :, :3]
image = image[:, :, ::-1]
# If grayscale. Convert to RGB for consistency.
if image.ndim != 3:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
return image
def load_depth(self, image_id):
"""Generate an image from the specs of the given image ID.
Typically this function loads the image from a file.
"""
info = self.image_info[image_id]
if info["source"] in ["CAMERA", "Real"]:
depth_path = info["path"] + '_depth.png'
depth = cv2.imread(depth_path, -1)
if len(depth.shape) == 3:
# This is encoded depth image, let's convert
depth16 = np.uint16(depth[:, :, 1]*256) + np.uint16(depth[:, :, 2]) # NOTE: RGB is actually BGR in opencv
depth16 = depth16.astype(np.uint16)
elif len(depth.shape) == 2 and depth.dtype == 'uint16':
depth16 = depth
else:
assert False, '[ Error ]: Unsupported depth type.'
else:
depth16 = None
return depth16
def image_reference(self, image_id):
"""Return the object data of the image."""
info = self.image_info[image_id]
if info["source"] in ["ShapeNetTOI", "Real"]:
return info["inst_dict"]
else:
super(self.__class__).image_reference(self, image_id)
def load_objs(self, image_id, is_normalized):
info = self.image_info[image_id]
meta_path = info["path"] + '_meta.txt'
inst_dict = info["inst_dict"]
with open(meta_path, 'r') as f:
lines = f.readlines()
Vs = []
Fs = []
for i, line in enumerate(lines):
words = line[:-1].split(' ')
inst_id = int(words[0])
if not inst_id in inst_dict:
continue
if len(words) == 3: ## real data
if words[2][-3:] == 'npz':
obj_name = words[2].replace('.npz', '_norm.obj')
mesh_file = os.path.join(self.config.OBJ_MODEL_DIR, 'real_val', obj_name)
else:
mesh_file = os.path.join(self.config.OBJ_MODEL_DIR, 'real_'+self.subset, words[2] + '.obj')
flip_flag = False
else:
assert len(words) == 4 ## synthetic data
mesh_file = os.path.join(self.config.OBJ_MODEL_DIR, self.subset, words[2], words[3], 'model.obj')
flip_flag = True
vertices, faces = utils.load_mesh(mesh_file, is_normalized, flip_flag)
Vs.append(vertices)
Fs.append(faces)
return Vs, Fs
def process_data(self, mask_im, coord_map, inst_dict, meta_path, load_RT=False):
# parsing mask
cdata = mask_im
cdata = np.array(cdata, dtype=np.int32)
# instance ids
instance_ids = list(np.unique(cdata))
instance_ids = sorted(instance_ids)
# remove background
assert instance_ids[-1] == 255
del instance_ids[-1]
cdata[cdata==255] = -1
assert(np.unique(cdata).shape[0] < 20)
num_instance = len(instance_ids)
h, w = cdata.shape
# flip z axis of coord map
coord_map = np.array(coord_map, dtype=np.float32) / 255
coord_map[:, :, 2] = 1 - coord_map[:, :, 2]
# Normal-NOTE: pre-process normal into format [0,1]
# normal_map = np.array(normal_map, dtype=np.float32) / 255
# normals = np.zeros((h, w, num_instance, 3), dtype=np.float32)
masks = np.zeros([h, w, num_instance], dtype=np.uint8)
coords = np.zeros((h, w, num_instance, 3), dtype=np.float32)
class_ids = np.zeros([num_instance], dtype=np.int_)
scales = np.zeros([num_instance, 3], dtype=np.float32)
with open(meta_path, 'r') as f:
lines = f.readlines()
scale_factor = np.zeros((len(lines), 3), dtype=np.float32)
for i, line in enumerate(lines):
words = line[:-1].split(' ')
if len(words) == 3:
## real scanned objs
if words[2][-3:] == 'npz':
npz_path = os.path.join(self.config.OBJ_MODEL_DIR, 'real_val', words[2])
with np.load(npz_path) as npz_file:
scale_factor[i, :] = npz_file['scale']
else:
bbox_file = os.path.join(self.config.OBJ_MODEL_DIR, 'real_'+self.subset, words[2]+'.txt')
scale_factor[i, :] = np.loadtxt(bbox_file)
scale_factor[i, :] /= np.linalg.norm(scale_factor[i, :])
else:
bbox_file = os.path.join(self.config.OBJ_MODEL_DIR, self.subset, words[2], words[3], 'bbox.txt')
bbox = np.loadtxt(bbox_file)
scale_factor[i, :] = bbox[0, :] - bbox[1, :]
i = 0
# delete ids of background objects and non-existing objects
inst_id_to_be_deleted = []
for inst_id in inst_dict.keys():
if inst_dict[inst_id] == 0 or (not inst_id in instance_ids):
inst_id_to_be_deleted.append(inst_id)
for delete_id in inst_id_to_be_deleted:
del inst_dict[delete_id]
for inst_id in instance_ids: # instance mask is one-indexed
if not inst_id in inst_dict:
continue
inst_mask = np.equal(cdata, inst_id)
assert np.sum(inst_mask) > 0
assert inst_dict[inst_id]
masks[:, :, i] = inst_mask
coords[:, :, i, :] = np.multiply(coord_map, np.expand_dims(inst_mask, axis=-1))
# normals[:, :, i, :] = np.multiply(normal_map, np.expand_dims(inst_mask, axis=-1))
# class ids is also one-indexed
class_ids[i] = inst_dict[inst_id]
scales[i, :] = scale_factor[inst_id - 1, :]
i += 1
# print('before: ', inst_dict)
masks = masks[:, :, :i]
coords = coords[:, :, :i, :]
coords = np.clip(coords, 0, 1)
# normals = normals[:, :, :i, :]
# normals = np.clip(normals, 0, 1)
class_ids = class_ids[:i]
scales = scales[:i]
# return masks, coords, normals, class_ids, scales
return masks, coords, class_ids, scales
def load_mask(self, image_id):
"""Generate instance masks for the objects in the image with the given ID.
"""
info = self.image_info[image_id]
#masks, coords, class_ids, scales, domain_label = None, None, None, None, None
if info["source"] in ["CAMERA", "Real"]:
domain_label = 0 ## has coordinate map loss
mask_path = info["path"] + '_mask.png'
coord_path = info["path"] + '_coord.png'
assert os.path.exists(mask_path), "{} is missing".format(mask_path)
assert os.path.exists(coord_path), "{} is missing".format(coord_path)
inst_dict = info['inst_dict']
meta_path = info["path"] + '_meta.txt'
mask_im = cv2.imread(mask_path)[:, :, 2]
coord_map = cv2.imread(coord_path)[:, :, :3]
coord_map = coord_map[:, :, (2, 1, 0)] # BGR -> RGB
masks, coords, class_ids, scales = self.process_data(mask_im, coord_map, inst_dict, meta_path)
### code for normals
# normal_path = info["path"] + '_normal.png'
# assert os.path.exists(normal_path), "{} is missing".format(normal_path)
# normal_map = cv2.imread(normal_path)[:, :, :3]
# normal_map = normal_map[:, :, ::-1] # Normal-NOTE: to check this
# masks, coords, normals, class_ids, scales = self.process_data(mask_im, coord_map, normal_map, inst_dict, meta_path)
elif info["source"]=="coco":
domain_label = 1 ## no coordinate map loss
instance_masks = []
class_ids = []
annotations = self.image_info[image_id]["annotations"]
# Build mask of shape [height, width, instance_count] and list
# of class IDs that correspond to each channel of the mask.
for annotation in annotations:
class_id = self.map_source_class_id(
"coco.{}".format(annotation['category_id']))
if class_id:
m = utils.annToMask(annotation, info["height"],
info["width"])
# Some objects are so small that they're less than 1 pixel area
# and end up rounded out. Skip those objects.
if m.max() < 1:
continue
instance_masks.append(m)
class_ids.append(class_id)
# Pack instance masks into an array