-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathimporters.py
1353 lines (1141 loc) · 49.5 KB
/
importers.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
"""Provides importer classes for importing data from different datasets.
DepthImporter provides interface for loading the data from a dataset, esp depth images.
ICVLImporter, NYUImporter, MSRAImporter are specific instances of different importers.
Copyright 2015 Markus Oberweger, ICG,
Graz University of Technology <oberweger@icg.tugraz.at>
This file is part of DeepPrior.
DeepPrior is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DeepPrior is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with DeepPrior. If not, see <http://www.gnu.org/licenses/>.
"""
import scipy.io
import numpy as np
from PIL import Image
import os
import progressbar as pb
import struct
from data.basetypes import DepthFrame, NamedImgSequence
from util.handdetector import HandDetector
from data.transformations import transformPoints2D
import cPickle
__author__ = "Paul Wohlhart <wohlhart@icg.tugraz.at>, Markus Oberweger <oberweger@icg.tugraz.at>"
__copyright__ = "Copyright 2015, ICG, Graz University of Technology, Austria"
__credits__ = ["Paul Wohlhart", "Markus Oberweger"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Markus Oberweger"
__email__ = "oberweger@icg.tugraz.at"
__status__ = "Development"
class DepthImporter(object):
"""
provide baisc functionality to load depth data
"""
def __init__(self, fx, fy, ux, uy):
"""
Initialize object
:param fx: focal length in x direction
:param fy: focal length in y direction
:param ux: principal point in x direction
:param uy: principal point in y direction
"""
self.fx = fx
self.fy = fy
self.ux = ux
self.uy = uy
self.depth_map_size = (320, 240)
self.refineNet = None
self.crop_joint_idx = 0
def jointsImgTo3D(self, sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((sample.shape[0], 3), np.float32)
for i in range(sample.shape[0]):
ret[i] = self.jointImgTo3D(sample[i])
return ret
def jointImgTo3D(self, sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((3,), np.float32)
# convert to metric using f
ret[0] = (sample[0]-self.ux)*sample[2]/self.fx
ret[1] = (sample[1]-self.uy)*sample[2]/self.fy
ret[2] = sample[2]
return ret
def joints3DToImg(self, sample):
"""
Denormalize sample from metric 3D to image coordinates
:param sample: joints in (x,y,z) with x,y and z in mm
:return: joints in (x,y,z) with x,y in image coordinates and z in mm
"""
ret = np.zeros((sample.shape[0], 3), np.float32)
for i in range(sample.shape[0]):
ret[i] = self.joint3DToImg(sample[i])
return ret
def joint3DToImg(self, sample):
"""
Denormalize sample from metric 3D to image coordinates
:param sample: joints in (x,y,z) with x,y and z in mm
:return: joints in (x,y,z) with x,y in image coordinates and z in mm
"""
ret = np.zeros((3,), np.float32)
# convert to metric using f
if sample[2] == 0.:
ret[0] = self.ux
ret[1] = self.uy
return ret
ret[0] = sample[0]/sample[2]*self.fx+self.ux
ret[1] = sample[1]/sample[2]*self.fy+self.uy
ret[2] = sample[2]
return ret
def getCameraProjection(self):
"""
Get homogenous camera projection matrix
:return: 4x4 camera projection matrix
"""
ret = np.zeros((4, 4), np.float32)
ret[0, 0] = self.fx
ret[1, 1] = self.fy
ret[2, 2] = 1.
ret[0, 2] = self.ux
ret[1, 2] = self.uy
ret[3, 2] = 1.
return ret
def getCameraIntrinsics(self):
"""
Get intrinsic camera matrix
:return: 3x3 intrinsic camera matrix
"""
ret = np.zeros((3, 3), np.float32)
ret[0, 0] = self.fx
ret[1, 1] = self.fy
ret[2, 2] = 1.
ret[0, 2] = self.ux
ret[1, 2] = self.uy
return ret
def showAnnotatedDepth(self, frame):
"""
Show the depth image
:param frame: image to show
:return:
"""
raise NotImplementedError("Must be overloaded by base!")
@staticmethod
def depthToPCL(dpt, T, background_val=0.):
# get valid points and transform
pts = np.asarray(np.where(~np.isclose(dpt, background_val))).transpose()
pts = np.concatenate([pts[:, [1, 0]] + 0.5, np.ones((pts.shape[0], 1), dtype='float32')], axis=1)
pts = np.dot(np.linalg.inv(np.asarray(T)), pts.T).T
pts = (pts[:, 0:2] / pts[:, 2][:, None]).reshape((pts.shape[0], 2))
# replace the invalid data
depth = dpt[(~np.isclose(dpt, background_val))]
# get x and y data in a vectorized way
row = (pts[:, 0] - 160.) / 241.42 * depth
col = (pts[:, 1] - 120.) / 241.42 * depth
# combine x,y,depth
return np.column_stack((row, col, depth))
# def loadRefineNetLazy(self, net):
# if isinstance(net, basestring):
# if os.path.exists(net):
# from net.scalenet import ScaleNet, ScaleNetParams
# comrefNetParams = ScaleNetParams(type=5, nChan=1, wIn=128, hIn=128, batchSize=1, resizeFactor=2,
# numJoints=1, nDims=3)
# self.refineNet = ScaleNet(np.random.RandomState(23455), cfgParams=comrefNetParams)
# self.refineNet.load(net)
# else:
# raise EnvironmentError("File not found: {}".format(net))
class ICVLImporter(DepthImporter):
"""
provide functionality to load data from the ICVL dataset
"""
def __init__(self, basepath, useCache=True, cacheDir='./cache/', refineNet=None):
"""
Constructor
:param basepath: base path of the ICVL dataset
:return:
"""
super(ICVLImporter, self).__init__(241.42, 241.42, 160., 120.) # see Qian et.al.
self.depth_map_size = (320, 240)
self.basepath = basepath
self.useCache = useCache
self.cacheDir = cacheDir
self.numJoints = 16
self.crop_joint_idx = 0
self.refineNet = refineNet
self.default_cubes = {'train': (250, 250, 250),
'test': (250, 250, 250),
'test_seq_2': (250, 250, 250)}
self.sides = {'train': 'right', 'test': 'right', 'test_seq_2': 'right'}
def loadDepthMap(self, filename):
"""
Read a depth-map
:param filename: file name to load
:return: image data of depth image
"""
img = Image.open(filename) # open image
assert len(img.getbands()) == 1 # ensure depth image
imgdata = np.asarray(img, np.float32)
return imgdata
def getDepthMapNV(self):
"""
Get the value of invalid depth values in the depth map
:return: value
"""
return 32001
def loadSequence(self, seqName, subSeq=None, Nmax=float('inf'), shuffle=False, rng=None, docom=False, cube=None,hand=None):
"""
Load an image sequence from the dataset
:param seqName: sequence name, e.g. train
:param subSeq: list of subsequence names, e.g. 0, 45, 122-5
:param Nmax: maximum number of samples to load
:return: returns named image sequence
"""
if (subSeq is not None) and (not isinstance(subSeq, list)):
raise TypeError("subSeq must be None or list")
if cube is None:
config = {'cube': self.default_cubes[seqName]}
else:
assert isinstance(cube, tuple)
assert len(cube) == 3
config = {'cube': cube}
print config['cube']
if subSeq is None:
pickleCache = '{}/{}_{}_None_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, HandDetector.detectionModeToString(docom, self.refineNet is not None), config['cube'][0])
else:
pickleCache = '{}/{}_{}_{}_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, ''.join(subSeq), HandDetector.detectionModeToString(docom, self.refineNet is not None), config['cube'][0])
if self.useCache:
if os.path.isfile(pickleCache):
print("Loading cache data from {}".format(pickleCache))
f = open(pickleCache, 'rb')
(seqName, data, config) = cPickle.load(f)
f.close()
# shuffle data
if shuffle and rng is not None:
print("Shuffling")
rng.shuffle(data)
if not(np.isinf(Nmax)):
return NamedImgSequence(seqName, data[0:Nmax], config)
else:
return NamedImgSequence(seqName, data, config)
# check for multiple subsequences
if subSeq is not None:
if len(subSeq) > 1:
missing = False
for i in range(len(subSeq)):
if not os.path.isfile('{}/{}_{}_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, subSeq[i], HandDetector.detectionModeToString(docom, self.refineNet is not None))):
missing = True
print("missing: {}".format(subSeq[i]))
break
if not missing:
# load first data
pickleCache = '{}/{}_{}_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, subSeq[0], HandDetector.detectionModeToString(docom, self.refineNet is not None))
print("Loading cache data from {}".format(pickleCache))
f = open(pickleCache, 'rb')
(seqName, fullData, config) = cPickle.load(f)
f.close()
# load rest of data
for i in range(1, len(subSeq)):
pickleCache = '{}/{}_{}_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, subSeq[i], HandDetector.detectionModeToString(docom, self.refineNet is not None))
print("Loading cache data from {}".format(pickleCache))
f = open(pickleCache, 'rb')
(seqName, data, config) = cPickle.load(f)
fullData.extend(data)
f.close()
# shuffle data
if shuffle and rng is not None:
print("Shuffling")
rng.shuffle(fullData)
if not(np.isinf(Nmax)):
return NamedImgSequence(seqName, fullData[0:Nmax], config)
else:
return NamedImgSequence(seqName, fullData, config)
# self.loadRefineNetLazy(self.refineNet)
# Load the dataset
objdir = '{}/Depth/'.format(self.basepath)
trainlabels = '{}/{}.txt'.format(self.basepath, seqName)
inputfile = open(trainlabels)
# center='{}/cens_{}.txt'.format(self.basepath,seqName)
# center_=open(center)
txt = 'Loading {}'.format(seqName)
pbar = pb.ProgressBar(maxval=len(inputfile.readlines()), widgets=[txt, pb.Percentage(), pb.Bar()])
pbar.start()
inputfile.seek(0)
#all_centers=center_.readlines()
data = []
i = 0
for line in inputfile:
# early stop
if len(data) >= Nmax:
break
part = line.split(' ')
# check for subsequences and skip them if necessary
subSeqName = ''
if subSeq is not None:
p = part[0].split('/')
# handle original data (unrotated '0') separately
if ('0' in subSeq) and len(p[0]) > 6:
pass
elif not('0' in subSeq) and len(p[0]) > 6:
i += 1
continue
elif (p[0] in subSeq) and len(p[0]) <= 6:
pass
elif not(p[0] in subSeq) and len(p[0]) <= 6:
i += 1
continue
if len(p[0]) <= 6:
subSeqName = p[0]
else:
subSeqName = '0'
dptFileName = '{}/{}'.format(objdir, part[0])
if not os.path.isfile(dptFileName):
print("File {} does not exist!".format(dptFileName))
i += 1
continue
dpt = self.loadDepthMap(dptFileName)
# if hand is not None:
# raise NotImplementedError()
# joints in image coordinates
gtorig = np.zeros((self.numJoints, 3), np.float32)
for joint in range(self.numJoints):
for xyz in range(0, 3):
gtorig[joint, xyz] = part[joint*3+xyz+1]
if hand:
dpt = np.fliplr(dpt)
gtorig[:, 0] = self.depth_map_size[0] - gtorig[:, 0]
# normalized joints in 3D coordinates
gt3Dorig = self.jointsImgTo3D(gtorig)
#self.showAnnotatedDepth(DepthFrame(dpt,gtorig,gtorig,0,gt3Dorig,gt3Dcrop,0,dptFileName,subSeqName,''))
# Detect hand
hd = HandDetector(dpt, self.fx, self.fy, refineNet=self.refineNet, importer=self)
if not hd.checkImage(1):
print("Skipping image {}, no content".format(dptFileName))
i += 1
continue
try:
# npcens=np.asarray(all_centers[i].split()).astype(np.float32)
# cen_=self.joint3DToImg(npcens)
dpt, M, com = hd.cropArea3D(com=gtorig[self.crop_joint_idx], size=config['cube'], docom=docom,dsize=(96,96))
except UserWarning:
print("Skipping image {}, no hand detected".format(dptFileName))
continue
com3D = self.jointImgTo3D(com)
gt3Dcrop = gt3Dorig - com3D # normalize to com
gtcrop = transformPoints2D(gtorig, M)
# print("{}".format(gt3Dorig))
# self.showAnnotatedDepth(DepthFrame(dpt,gtorig,gtcrop,M,gt3Dorig,gt3Dcrop,com3D,dptFileName,subSeqName,''))
data.append(DepthFrame(dpt.astype(np.float32), gtorig, gtcrop, M, gt3Dorig, gt3Dcrop, com3D, dptFileName,
subSeqName, 'left', {},cube))
pbar.update(i)
i += 1
inputfile.close()
pbar.finish()
print("Loaded {} samples.".format(len(data)))
if self.useCache:
print("Save cache data to {}".format(pickleCache))
f = open(pickleCache, 'wb')
cPickle.dump((seqName, data, config), f, protocol=cPickle.HIGHEST_PROTOCOL)
f.close()
# shuffle data
if shuffle and rng is not None:
print("Shuffling")
rng.shuffle(data)
return NamedImgSequence(seqName, data, config)
def loadBaseline(self, filename, firstName=False):
"""
Load baseline data
:param filename: file name of data
:return: list with joint coordinates
"""
def nonblank_lines(f):
for l in f:
line = l.rstrip()
if line:
yield line
inputfile = open(filename)
inputfile.seek(0)
if firstName == True:
off = 1
else:
off = 0
data = []
for line in nonblank_lines(inputfile):
part = line.strip().split(' ')
# joints in image coordinates
ev = np.zeros((self.numJoints, 3), np.float32)
for joint in range(ev.shape[0]):
for xyz in range(0, 3):
ev[joint, xyz] = part[joint*3+xyz+off]
gt3Dworld = self.jointsImgTo3D(ev)
data.append(gt3Dworld)
return data
def loadBaseline2D(self, filename, firstName=False):
"""
Load baseline data
:param filename: file name of data
:return: list with joint coordinates
"""
inputfile = open(filename)
inputfile.seek(0)
if firstName is True:
off = 1
else:
off = 0
data = []
for line in inputfile:
part = line.split(' ')
# joints in image coordinates
ev = np.zeros((self.numJoints,2),np.float32)
for joint in range(ev.shape[0]):
for xyz in range(0, 2):
ev[joint,xyz] = part[joint*3+xyz+off]
data.append(ev)
return data
def showAnnotatedDepth(self, frame):
"""
Show the depth image
:param frame: image to show
:return:
"""
import matplotlib
import matplotlib.pyplot as plt
print("img min {}, max {}".format(frame.dpt.min(), frame.dpt.max()))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(frame.dpt, cmap=matplotlib.cm.jet, interpolation='nearest')
ax.scatter(frame.gtcrop[:, 0], frame.gtcrop[:, 1])
ax.plot(frame.gtcrop[0:4, 0], frame.gtcrop[0:4, 1], c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[4:7, 0])),
np.hstack((frame.gtcrop[0, 1], frame.gtcrop[4:7, 1])), c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[7:10, 0])),
np.hstack((frame.gtcrop[0, 1], frame.gtcrop[7:10, 1])), c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[10:13, 0])),
np.hstack((frame.gtcrop[0, 1], frame.gtcrop[10:13, 1])), c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[13:16, 0])),
np.hstack((frame.gtcrop[0, 1], frame.gtcrop[13:16, 1])), c='r')
def format_coord(x, y):
numrows, numcols = frame.dpt.shape
col = int(x + 0.5)
row = int(y + 0.5)
if col >= 0 and col < numcols and row >= 0 and row < numrows:
z = frame.dpt[row, col]
return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z)
else:
return 'x=%1.4f, y=%1.4f' % (x, y)
ax.format_coord = format_coord
for i in range(frame.gtcrop.shape[0]):
ax.annotate(str(i), (int(frame.gtcrop[i, 0]), int(frame.gtcrop[i, 1])))
plt.show()
class MSRA15Importer(DepthImporter):
"""
provide functionality to load data from the MSRA 2015 dataset
faulty images:
- P2/TIP: 172, 173,174
- P2/MP: 173, 174, 175, 345-354, 356, 359, 360
- P3/T: 120, 489
- P8/4: 168
"""
def __init__(self, basepath, useCache=True, cacheDir='./cache/', refineNet=None, detectorNet=None, derotNet=None):
"""
Constructor
:param basepath: base path of the MSRA dataset
:return:
"""
super(MSRA15Importer, self).__init__(241.42, 241.42, 160., 120.) # see Sun et.al.
self.depth_map_size = (320, 240)
self.basepath = basepath
self.useCache = useCache
self.cacheDir = cacheDir
self.refineNet = refineNet
self.derotNet = derotNet
self.detectorNet = detectorNet
self.numJoints = 21
self.crop_joint_idx = 9
self.default_cubes = {'P0': (200, 200, 200),
'P1': (200, 200, 200),
'P2': (200, 200, 200),
'P3': (180, 180, 180),
'P4': (180, 180, 180),
'P5': (180, 180, 180),
'P6': (170, 170, 170),
'P7': (160, 160, 160),
'P8': (150, 150, 150)}
self.sides = {'P0': 'right', 'P1': 'right', 'P2': 'right', 'P3': 'right', 'P4': 'right', 'P5': 'right',
'P6': 'right', 'P7': 'right', 'P8': 'right'}
def loadDepthMap(self, filename):
"""
Read a depth-map
:param filename: file name to load
:return: image data of depth image
"""
with open(filename, 'rb') as f:
# first 6 uint define the full image
width = struct.unpack('i', f.read(4))[0]
height = struct.unpack('i', f.read(4))[0]
left = struct.unpack('i', f.read(4))[0]
top = struct.unpack('i', f.read(4))[0]
right = struct.unpack('i', f.read(4))[0]
bottom = struct.unpack('i', f.read(4))[0]
patch = np.fromfile(f, dtype='float32', sep="")
imgdata = np.zeros((height, width), dtype='float32')
imgdata[top:bottom, left:right] = patch.reshape([bottom-top, right-left])
# points1=[left,right,right,left,left]
# points2=[top,top,bottom,bottom,top]
# import matplotlib.pyplot as plt
# plt.imshow(imgdata,cmap='brg')
# plt.plot(points1,points2,c='r')
# plt.show()
return imgdata
def getDepthMapNV(self):
"""
Get the value of invalid depth values in the depth map
:return: value
"""
return 32001
def loadSequence(self, seqName, subSeq=None, Nmax=float('inf'), shuffle=False, rng=None, docom=False, cube=None, hand=None):
"""
Load an image sequence from the dataset
:param seqName: sequence name, e.g. subject1
:param Nmax: maximum number of samples to load
:return: returns named image sequence
"""
if (subSeq is not None) and (not isinstance(subSeq, list)):
raise TypeError("subSeq must be None or list")
if cube is None:
config = {'cube': self.default_cubes[seqName]}
else:
assert isinstance(cube, tuple)
assert len(cube) == 3
config = {'cube': cube}
if subSeq is None:
pickleCache = '{}/{}_{}_None_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, HandDetector.detectionModeToString(docom, self.refineNet is not None), config['cube'][0])
else:
pickleCache = '{}/{}_{}_{}_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, ''.join(subSeq), HandDetector.detectionModeToString(docom, self.refineNet is not None), config['cube'][0])
if self.useCache & os.path.isfile(pickleCache):
print("Loading cache data from {}".format(pickleCache))
f = open(pickleCache, 'rb')
(seqName, data, config) = cPickle.load(f)
f.close()
# shuffle data
if shuffle and rng is not None:
print("Shuffling")
rng.shuffle(data)
if not(np.isinf(Nmax)):
return NamedImgSequence(seqName, data[0:Nmax], config)
else:
return NamedImgSequence(seqName, data, config)
# self.loadRefineNetLazy(self.refineNet)
# Load the dataset
objdir = '{}/{}/'.format(self.basepath, seqName)
subdirs = sorted([name for name in os.listdir(objdir) if os.path.isdir(os.path.join(objdir, name))])
print subdirs
txt = 'Loading {}'.format(seqName)
nImgs = sum([len(files) for r, d, files in os.walk(objdir)]) // 2
print nImgs
pbar = pb.ProgressBar(maxval=nImgs, widgets=[txt, pb.Percentage(), pb.Bar()])
pbar.start()
# comlabels='{}/center/center_test_{}_refined.txt'.format(self.basepath,seqName[1])
# print comlabels
# comsfile = open(comlabels, 'r')
data = []
pi = 0
for subdir in subdirs:
# check for subsequences and skip them if necessary
subSeqName = ''
if subSeq is not None:
if subdir not in subSeq:
continue
subSeqName = subdir
# iterate all subdirectories
trainlabels = '{}/{}/joint.txt'.format(objdir, subdir)
inputfile = open(trainlabels)
# read number of samples
nImgs = int(inputfile.readline())
for i in range(nImgs):
scale = np.random.randint(0, 6)
# early stop
if len(data) >= Nmax:
break
# com=comsfile.readline()
# com_=com.split()
# com_=np.asarray(com_,np.float)
# com2D = self.joint3DToImg(com_)
line = inputfile.readline()
part = line.split(' ')
dptFileName = '{}/{}/{}_depth.bin'.format(objdir, subdir, str(i).zfill(6))
if not os.path.isfile(dptFileName):
print("File {} does not exist!".format(dptFileName))
continue
dpt = self.loadDepthMap(dptFileName)
if hand is not None:
raise NotImplementedError()
# joints in image coordinates
gt3Dorig = np.zeros((self.numJoints, 3), np.float32)
for joint in range(gt3Dorig.shape[0]):
for xyz in range(0, 3):
gt3Dorig[joint, xyz] = part[joint*3+xyz]
# invert axis
# gt3Dorig[:, 0] *= (-1.)
# gt3Dorig[:, 1] *= (-1.)
gt3Dorig[:, 2] *= (-1.)
# normalized joints in 3D coordinates
gtorig = self.joints3DToImg(gt3Dorig)
# print gt3D
# self.showAnnotatedDepth(DepthFrame(dpt,gtorig,gtorig,0,gt3Dorig,gt3Dcrop,com3D,dptFileName,'',''))
# Detect hand
hd = HandDetector(dpt, self.fx, self.fy, refineNet=self.refineNet, importer=self)
if not hd.checkImage(1.):
print("Skipping image {}, no content".format(dptFileName))
continue
try:
varcube = 150 + 10 * scale
cube_0 = (varcube, varcube, varcube)
if cube is None:
cube_ = cube_0
else:
cube_ = cube
dpt, M, com = hd.cropArea3D(com=gtorig[self.crop_joint_idx], size=cube_, docom=docom,dsize=(96,96))
#print cube_
# import matplotlib.pyplot as plt
# plt.imshow(dpt)
# plt.show()
except UserWarning:
print("Skipping image {}, no hand detected".format(dptFileName))
continue
com3D = self.jointImgTo3D(com)
gt3Dcrop = gt3Dorig - com3D # normalize to com
gtcrop = transformPoints2D(gtorig, M)
# print("{}".format(gt3Dorig))
# self.showAnnotatedDepth(DepthFrame(dpt,gtorig,gtcrop,M,gt3Dorig,gt3Dcrop,com3D,dptFileName,'','',{}))
data.append(DepthFrame(dpt.astype(np.float32), gtorig, gtcrop, M, gt3Dorig, gt3Dcrop, com3D,
dptFileName, subSeqName, self.sides[seqName], {},cube_))
pbar.update(pi)
pi += 1
inputfile.close()
pbar.finish()
print("Loaded {} samples.".format(len(data)))
if self.useCache:
print("Save cache data to {}".format(pickleCache))
f = open(pickleCache, 'wb')
cPickle.dump((seqName, data, config), f, protocol=cPickle.HIGHEST_PROTOCOL)
f.close()
# shuffle data
if shuffle and rng is not None:
print("Shuffling")
rng.shuffle(data)
return NamedImgSequence(seqName, data, config)
def jointsImgTo3D(self, sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((sample.shape[0], 3), np.float32)
for i in xrange(sample.shape[0]):
ret[i] = self.jointImgTo3D(sample[i])
return ret
def jointImgTo3D(self, sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((3,), np.float32)
ret[0] = (sample[0] - self.ux) * sample[2] / self.fx
ret[1] = (self.uy - sample[1]) * sample[2] / self.fy
ret[2] = sample[2]
return ret
def joints3DToImg(self, sample):
"""
Denormalize sample from metric 3D to image coordinates
:param sample: joints in (x,y,z) with x,y and z in mm
:return: joints in (x,y,z) with x,y in image coordinates and z in mm
"""
ret = np.zeros((sample.shape[0], 3), np.float32)
for i in xrange(sample.shape[0]):
ret[i] = self.joint3DToImg(sample[i])
return ret
def joint3DToImg(self, sample):
"""
Denormalize sample from metric 3D to image coordinates
:param sample: joints in (x,y,z) with x,y and z in mm
:return: joints in (x,y,z) with x,y in image coordinates and z in mm
"""
ret = np.zeros((3, ), np.float32)
if sample[2] == 0.:
ret[0] = self.ux
ret[1] = self.uy
return ret
ret[0] = sample[0]/sample[2]*self.fx+self.ux
ret[1] = self.uy-sample[1]/sample[2]*self.fy
ret[2] = sample[2]
return ret
def getCameraIntrinsics(self):
"""
Get intrinsic camera matrix
:return: 3x3 intrinsic camera matrix
"""
ret = np.zeros((3, 3), np.float32)
ret[0, 0] = self.fx
ret[1, 1] = -self.fy
ret[2, 2] = 1
ret[0, 2] = self.ux
ret[1, 2] = self.uy
return ret
def getCameraProjection(self):
"""
Get homogenous camera projection matrix
:return: 4x4 camera projection matrix
"""
ret = np.zeros((4, 4), np.float32)
ret[0, 0] = self.fx
ret[1, 1] = -self.fy
ret[2, 2] = 1.
ret[0, 2] = self.ux
ret[1, 2] = self.uy
ret[3, 2] = 1.
return ret
def showAnnotatedDepth(self, frame):
"""
Show the depth image
:param frame: image to show
:return:
"""
import matplotlib
import matplotlib.pyplot as plt
print("img min {}, max {}".format(frame.dpt.min(),frame.dpt.max()))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(frame.dpt, cmap=matplotlib.cm.jet, interpolation='nearest')
ax.scatter(frame.gtcrop[:, 0], frame.gtcrop[:, 1])
ax.plot(frame.gtcrop[0:5, 0], frame.gtcrop[0:5, 1], c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[5:9, 0])), np.hstack((frame.gtcrop[0, 1], frame.gtcrop[5:9, 1])), c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[9:13, 0])), np.hstack((frame.gtcrop[0, 1], frame.gtcrop[9:13, 1])), c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[13:17, 0])), np.hstack((frame.gtcrop[0, 1], frame.gtcrop[13:17, 1])), c='r')
ax.plot(np.hstack((frame.gtcrop[0, 0], frame.gtcrop[17:21, 0])), np.hstack((frame.gtcrop[0, 1], frame.gtcrop[17:21, 1])), c='r')
def format_coord(x, y):
numrows, numcols = frame.dpt.shape
col = int(x+0.5)
row = int(y+0.5)
if col>=0 and col<numcols and row>=0 and row<numrows:
z = frame.dpt[row, col]
return 'x=%1.4f, y=%1.4f, z=%1.4f'%(x, y, z)
else:
return 'x=%1.4f, y=%1.4f'%(x, y)
ax.format_coord = format_coord
for i in range(frame.gtcrop.shape[0]):
ax.annotate(str(i), (int(frame.gtcrop[i, 0]), int(frame.gtcrop[i, 1])))
plt.show()
@staticmethod
def depthToPCL(dpt, T, background_val=0.):
# get valid points and transform
pts = np.asarray(np.where(~np.isclose(dpt, background_val))).transpose()
pts = np.concatenate([pts[:, [1, 0]] + 0.5, np.ones((pts.shape[0], 1), dtype='float32')], axis=1)
pts = np.dot(np.linalg.inv(np.asarray(T)), pts.T).T
pts = (pts[:, 0:2] / pts[:, 2][:, None]).reshape((pts.shape[0], 2))
# replace the invalid data
depth = dpt[(~np.isclose(dpt, background_val))]
# get x and y data in a vectorized way
row = (pts[:, 0] - 160.) / 241.42 * depth
col = (120. - pts[:, 1]) / 241.42 * depth
# combine x,y,depth
return np.column_stack((row, col, depth))
class NYUImporter(DepthImporter):
"""
provide functionality to load data from the NYU hand dataset
"""
def __init__(self, basepath, useCache=True, cacheDir='./cache/', refineNet=None, allJoints=False):
"""
Constructor
:param basepath: base path of the ICVL dataset
:return:
"""
super(NYUImporter, self).__init__(588.03, 587.07, 320., 240.)
self.depth_map_size = (640, 480)
self.basepath = basepath
self.useCache = useCache
self.cacheDir = cacheDir
self.allJoints = allJoints
self.numJoints = 36
if self.allJoints:
self.crop_joint_idx = 32
else:
self.crop_joint_idx = 13
self.default_cubes = {'train': (300, 300, 300),
'test_1': (300, 300, 300),
'test_2': (250, 250, 250),
'test': (300, 300, 300),
'train_synth': (300, 300, 300),
'test_synth_1': (300, 300, 300),
'test_synth_2': (250, 250, 250),
'test_synth': (300, 300, 300)}
self.sides = {'train': 'right', 'test_1': 'right', 'test_2': 'right', 'test': 'right', 'train_synth': 'right',
'test_synth_1': 'right', 'test_synth_2': 'right', 'test_synth': 'right'}
# joint indices used for evaluation of Tompson et al.
self.restrictedJointsEval = [0, 3, 6, 9, 12, 15, 18, 21, 24, 25, 27, 30, 31, 32]
self.refineNet = refineNet
def loadDepthMap(self, filename):
"""
Read a depth-map
:param filename: file name to load
:return: image data of depth image
"""
img = Image.open(filename)
# top 8 bits of depth are packed into green channel and lower 8 bits into blue
assert len(img.getbands()) == 3
r, g, b = img.split()
r = np.asarray(r, np.int32)
g = np.asarray(g, np.int32)
b = np.asarray(b, np.int32)
dpt = np.bitwise_or(np.left_shift(g, 8), b)
imgdata = np.asarray(dpt, np.float32)
return imgdata
def getDepthMapNV(self):
"""
Get the value of invalid depth values in the depth map
:return: value
"""
return 32001
def loadSequence(self, seqName, Nmax=float('inf'), shuffle=False, rng=None, docom=False, cube=None, hand=None):
"""
Load an image sequence from the dataset
:param seqName: sequence name, e.g. train
:param Nmax: maximum number of samples to load
:return: returns named image sequence
"""
if cube is None:
config = {'cube': (0,0,0)}
else:
assert isinstance(cube, tuple)
assert len(cube) == 3
config = {'cube': cube}
pickleCache = '{}/{}_{}_{}_{}_{}_cache.pkl'.format(self.cacheDir, self.__class__.__name__, seqName, self.allJoints, HandDetector.detectionModeToString(docom, self.refineNet is not None), config['cube'][0])
if self.useCache:
if os.path.isfile(pickleCache):
print("Loading cache data from {}".format(pickleCache))
f = open(pickleCache, 'rb')
(seqName, data, config) = cPickle.load(f)
f.close()
# shuffle data
if shuffle and rng is not None:
print("Shuffling")
rng.shuffle(data)
if not(np.isinf(Nmax)):
return NamedImgSequence(seqName, data[0:Nmax], config)
else:
return NamedImgSequence(seqName, data, config)
# self.loadRefineNetLazy(self.refineNet)
# Load the dataset
objdir = '{}/{}/'.format(self.basepath, seqName)
trainlabels = '{}/{}/joint_data.mat'.format(self.basepath, seqName)
print trainlabels
comlabels='{}/{}_NYU.txt'.format(self.basepath,seqName)
f = open(comlabels, 'r')