-
Notifications
You must be signed in to change notification settings - Fork 3
/
library.py
1684 lines (1463 loc) · 70.6 KB
/
library.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
import numpy as np
import cv2
import math
import time
import glob, os
import random
import psutil
import ctypes
from datetime import datetime
MaxSameKP_dist = 5 # pixels
MaxSameKP_angle = 10 # degrees
class ClassSIFTparams():
def __init__(self, nfeatures = 0, nOctaveLayers = 3, contrastThreshold = 0.04, edgeThreshold = 10, sigma = 1.6, firstOctave = -1, sift_init_sigma = 0.5, graydesc = True):
self.nOctaves = 4
self.nfeatures = nfeatures
self.nOctaveLayers = nOctaveLayers
self.contrastThreshold = contrastThreshold
self.edgeThreshold = edgeThreshold
self.sigma = sigma
self.firstOctave = firstOctave
self.sift_init_sigma = sift_init_sigma
self.graydesc = graydesc
self.flt_epsilon = 1.19209e-07
self.lambda_descr = 6
self.new_radius_descr = 29.5
siftparams = ClassSIFTparams(graydesc = True)
class GenAffine():
def __init__(self, path_to_imgs, tmax = 75, zmax = 1.6, save_path = "/tmp", saveMem = True, normalizeIMG=True, ActiveRadius=int(siftparams.new_radius_descr*2+1), ReducedRadius=0.25, DoBigEpochs=False, DryRun = False, inImageNegative=False, UseIMASgenerator=False):
self.path_to_imgs = path_to_imgs
self.save_path = save_path
TouchDir(save_path)
self.UseIMASgenerator = UseIMASgenerator
self.max_simu_zoom = zmax
self.max_simu_theta = np.deg2rad(tmax)
self.imgs_path = ()
self.imgs = []
self.imgs_gray = []
self.KPlists = []
self.saveMem = saveMem
self.imgdivfactor = 1.0
if normalizeIMG==True:
self.imgdivfactor = 255.0
ar = np.float32(ActiveRadius)
rr = np.float32(ReducedRadius)
self.vecdivfactor = ar/rr
self.vectraslation = (1.0 - rr)/2.0 #+rr/2.0
self.gen_P_list = []
self.gen_GT_list = []
self.OutputNegativePatch = inImageNegative
self.gen_GTn_list = []
self.gen_dirs = []
# self.Avec_tras = np.float32( [0.0, -4*math.pi, -7.0, -4*math.pi, -4.0*siftparams.new_radius_descr, -4.0*siftparams.new_radius_descr])
# self.Avec_factor = np.float32([2.0, 8.0*math.pi, 16.0, 8.0*math.pi, 8.0*siftparams.new_radius_descr, 8.0*siftparams.new_radius_descr])
self.Avec_tras = np.float32( [0.0, 0.0, 1.0, 0.0, -4.0*siftparams.new_radius_descr, -4.0*siftparams.new_radius_descr])
self.Avec_factor = np.float32([2.0, 2.0*math.pi, 8.0, math.pi, 2.0*4.0*siftparams.new_radius_descr, 2.0*4.0*siftparams.new_radius_descr])
self.A_tras = np.float32( [-8.0, -8.0, -1.0*siftparams.new_radius_descr, -8.0, -8.0, -1.0*siftparams.new_radius_descr])
self.A_factor = np.float32([16.0, 16.0, 2.0*siftparams.new_radius_descr, 16.0, 16.0, 2.0*siftparams.new_radius_descr])
self.BigAffineVec = False
self.DoBigEpochs = DoBigEpochs
self.LastTimeDataChecked = time.time()
self.GAid = random.randint(0,1000)
set_big_epoch_number(self,0)
if not DryRun:
if self.OutputNegativePatch:
for dir in glob.glob(self.save_path+"/inImageNegatives/*.npz"):
self.gen_dirs.append(dir)
else:
for dir in glob.glob(self.save_path+"/*.npz"):
self.gen_dirs.append(dir)
imgspaths = (self.path_to_imgs+"/*.png", self.path_to_imgs+"/*.jpg")
for ips in imgspaths:
for file in glob.glob(ips):
self.imgs_path += tuple([file])
if saveMem==False:
self.imgs.append( cv2.imread(file) )
self.imgs_gray.append( cv2.cvtColor(self.imgs[len(self.imgs)-1],cv2.COLOR_BGR2GRAY) )
self.KPlists.append( ComputeSIFTKeypoints(self.imgs[len(self.imgs)-1]) )
assert (len(self.imgs_path)>0), 'We need at least one image in folder '+self.path_to_imgs
def NormalizeVector(self,vec):
''' For stability reasons, the network should be trained with a normalized vector.
Use this function to normalize a vector in patch coordinates and make it compatile
with the output of the network.
'''
return vec/self.vecdivfactor + self.vectraslation
def UnNormalizeVector(self,vec):
''' For stability reasons, the network should be trained with a normalized vector.
Use this function to unnormalize an output vector of the network.
The resulting vector info will be now in patch coordinates.
'''
return (vec - self.vectraslation)*self.vecdivfactor
def Nvec2Avec(self, normalizedvec):
''' Computes the passage from a normalized vector to the affine_decomp vector
normalizedvec has the flatten normalized info of points x1,...,x8, such that
A(ci) = xi for i=1,...,4
A^-1(ci) = xi for i=5,...,8
where ci are the corners of a patch
'''
A = np.array(self.AffineFromNormalizedVector(normalizedvec))
avec = (affine_decomp(A)-self.Avec_tras)/self.Avec_factor
assert np.greater_equal(avec,np.zeros(np.shape(avec))).all() and np.less_equal(avec,np.ones(np.shape(avec))).all(), 'Failed attempt to Normalize affine parameters in Nvec2Avec \n ' + str(avec)
if self.BigAffineVec:
Ai = np.array(cv2.invertAffineTransform(A))
aivec = (affine_decomp(Ai)-self.Avec_tras)/self.Avec_factor
assert np.greater_equal(aivec,np.zeros(np.shape(aivec))).all() and np.less_equal(aivec,np.ones(np.shape(aivec))).all(), 'Failed attempt to Normalize inverse affine parameters in Nvec2Avec \n ' + str(aivec)
return np.concatenate((avec,aivec))
return avec
def Avec2Nvec(self, affinevec, d = np.int32(siftparams.new_radius_descr*2)+1):
''' Computes the passage from an affine_decomp vector to a normalized vector which
has the flatten normalized info of points x1,...,x8, such that
A(ci) = xi for i=1,...,4
A^-1(ci) = xi for i=5,...,8
where ci are the corners of a patch
'''
SquarePatch = SquareOrderedPts(d,d,CV=False)
avec = affine_decomp2affine(affinevec[0:6]*self.Avec_factor + self.Avec_tras)
A = np.reshape(avec,(2,3))
evec = np.zeros((16),np.float32)
evec[0:8] = self.NormalizeVector( Pts2Flatten(AffineArrayCoor(SquarePatch,A)) )
if self.BigAffineVec:
aivec = affine_decomp2affine(affinevec[6:12]*self.Avec_factor + self.Avec_tras)
Ai = np.reshape(aivec,(2,3))
evec[8:16] = self.NormalizeVector( Pts2Flatten(AffineArrayCoor(SquarePatch,Ai)) )
else:
evec[8:16] = self.NormalizeVector( Pts2Flatten(AffineArrayCoor(SquarePatch,cv2.invertAffineTransform(A))) )
return evec
def AffineFromNormalizedVector(self,vec0, d = np.int32(siftparams.new_radius_descr*2)+1, use_inv_pts=True):
''' Computes the affine map fitting vec0.
vec0 has the flatten normalized info of points x1,...,x8, such that
A(ci) = xi for i=1,...,4
A^-1(ci) = xi for i=5,...,8
where ci are the corners of a patch
'''
vec = self.UnNormalizeVector(vec0.copy())
X = SquareOrderedPts(d,d,CV=False)
Y1 = Flatten2Pts(vec[0:8])
if use_inv_pts:
Y2 = Flatten2Pts(vec[8:16])
return AffineFit(np.concatenate((X, Y2)),np.concatenate((Y1, X)))
else:
return AffineFit(X,Y1)
def MountGenData(self, MaxData = 31500):
start_time = time.time()
if len(self.gen_dirs)>0:
i = random.randint(0,len(self.gen_dirs)-1)
path = self.gen_dirs.pop(i)
print("\n Loading Gen Data (MaxData = "+str(MaxData)+") from "+path+" \n", end="")
try:
npzfile = np.load(path)
except:
print("Problem loading file: ",path)
vec_list = npzfile['vec_list']
p1_list = npzfile['p1_list']
p2_list = npzfile['p2_list']
if self.OutputNegativePatch:
pN_list = npzfile['pN_list']
vecN_list = npzfile['vecN_list']
assert len(vec_list)==len(p1_list) and len(vec_list)==len(p2_list)
for i in range(0,len(vec_list)):
if self.OutputNegativePatch:
self.gen_P_list.append( np.dstack((p1_list[i].astype(np.float32)/self.imgdivfactor, p2_list[i].astype(np.float32)/self.imgdivfactor, pN_list[i].astype(np.float32)/self.imgdivfactor)) )
self.gen_GTn_list.append( self.NormalizeVector(vecN_list[i]) )
else:
self.gen_P_list.append( np.dstack((p1_list[i].astype(np.float32)/self.imgdivfactor, p2_list[i].astype(np.float32)/self.imgdivfactor)) )
self.gen_GT_list.append( self.NormalizeVector(vec_list[i]) )
if np.int32( len(self.gen_P_list) % np.int32(MaxData/10) )==0:
elapsed_time = time.time() - start_time
tstr = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
start_time = time.time()
print("\n "+str(MaxData/10) +" items loaded in "+ tstr, end="")
# print("\r "+ str(MaxData/10) +" items loaded in "+ tstr, end="")
if len(self.gen_P_list)>=MaxData:
print("\n Maximal data items attained !")
break
def ScatteredGenData_2_BlockData(self, BlockItems = 31000):
hours, minutes, seconds = HumanElapsedTime(self.LastTimeDataChecked,time.time())
if minutes>30 or hours>0:
self.LastTimeDataChecked = time.time()
globtxt_list = []
SaveData = False
if self.OutputNegativePatch:
toSearch = "/*.vectorN.txt"
else:
toSearch = "/*.vector.txt"
for file in glob.glob(self.save_path+toSearch):
if self.OutputNegativePatch:
globtxt_list.append(file[0:(len(file)-11)]+"vector.txt")
else:
globtxt_list.append(file)
if len(globtxt_list)==BlockItems:
SaveData = True
break
if SaveData:
start_time = time.time()
vec_list = []
vecN_list = []
p1_list = []
p2_list = []
pN_list = []
for file in globtxt_list:
try:
vec = np.loadtxt(file)
if len(vec)!=16:
print("There was an error loading generated vector. That pair will be skipped !")
continue
os.remove(file)
file = file[0:(len(file)-10)]
p1 = cv2.imread(file+"p1.png")
p2 = cv2.imread(file+"p2.png")
if self.OutputNegativePatch:
vecN = np.loadtxt(file+"vectorN.txt")
pN = cv2.imread(file+"pN.png")
if (siftparams.graydesc):
p1 = cv2.cvtColor(p1, cv2.COLOR_BGR2GRAY).astype(np.uint8)
p2 = cv2.cvtColor(p2, cv2.COLOR_BGR2GRAY).astype(np.uint8)
if self.OutputNegativePatch:
pN = cv2.cvtColor(pN, cv2.COLOR_BGR2GRAY).astype(np.uint8)
vec_list.append(vec)
p1_list.append(p1)
p2_list.append(p2)
os.remove(file+"p1.png")
os.remove(file+"p2.png")
if self.OutputNegativePatch:
pN_list.append(pN)
vecN_list.append(vecN)
os.remove(file+"pN.png")
os.remove(file+"vectorN.txt")
except:
print("Error loading data. That pair will be skipped !")
ts = datetime.now().strftime("%d-%m-%Y_%H:%M:%S")
if self.OutputNegativePatch:
np.savez(self.save_path+'/inImageNegatives/block_'+ts,vec_list=vec_list,p1_list=p1_list,p2_list=p2_list, pN_list=pN_list, vecN_list=vecN_list)
else:
np.savez(self.save_path+'/block_'+ts,vec_list=vec_list,p1_list=p1_list,p2_list=p2_list)
elapsed_time = time.time() - start_time
tstr = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
print("A block of data was created in "+ tstr)
def AvailableGenData(self):
return len(self.gen_P_list)+len(self.gen_dirs)
def Fast_gen_affine_patches(self, AllOutput=True):
if self.DoBigEpochs and len(self.gen_P_list)<=10 and len(self.gen_dirs)==0:
set_big_epoch_number(self,get_big_epoch_number(self)+1)
if self.OutputNegativePatch:
for dir in glob.glob(self.save_path+"/inImageNegatives/*.npz"):
self.gen_dirs.append(dir)
else:
for dir in glob.glob(self.save_path+"/*.npz"):
self.gen_dirs.append(dir)
while len(self.gen_P_list)<=10 and len(self.gen_dirs)>0:
self.MountGenData()
if (len(self.gen_P_list)==0):
return self.gen_affine_patches(AllOutput=AllOutput)
else:
i = random.randint(0,len(self.gen_P_list)-1)
if self.OutputNegativePatch:
if AllOutput:
return self.gen_P_list.pop(i), self.gen_GT_list.pop(i), self.gen_GTn_list.pop(i)
else:
return self.gen_P_list.pop(i), self.gen_GT_list.pop(i)
else:
return self.gen_P_list.pop(i), self.gen_GT_list.pop(i)
def gen_affine_patches(self, AllOutput=True):
im1_zoom = random.uniform(1.0, self.max_simu_zoom)
im2_zoom = random.uniform(1.0, self.max_simu_zoom)
theta1 = random.uniform(0.0, self.max_simu_theta)
theta2 = random.uniform(0.0, self.max_simu_theta)
im1_t = 1.0/np.cos(theta1)
im2_t = 1.0/np.cos(theta2)
im1_phi1 = np.rad2deg( random.uniform(0.0, math.pi) )
im2_phi1 = np.rad2deg( random.uniform(0.0, math.pi) )
im1_phi2 = np.rad2deg( random.uniform(0.0, 2*math.pi) )
im2_phi2 = np.rad2deg( random.uniform(0.0, 2*math.pi) )
while True:
idx_img = random.randint(0,len(self.imgs_path)-1)
if self.saveMem==True:
img = cv2.cvtColor(cv2.imread(self.imgs_path[idx_img]), cv2.COLOR_BGR2GRAY)
KPlist = ComputeSIFTKeypoints(img)
else:
img = self.imgs[idx_img]
KPlist = self.KPlists[idx_img]
if self.UseIMASgenerator:
imas_kps = IMAS_keypoints(img)
imas_kps.Compute_IMAS_Keypoints_from_image(SIFTAID=False)
idxs = imas_kps.GetOrderedImasKpIdxs()
if len(idxs)==0:
continue
maxnum = np.min([len(idxs), 100])
idxs = idxs[0:maxnum]
pts = [imas_kps.Idx2Pt(idx) for idx in idxs]
KPlist0 = []
for pt0 in pts:
norms = [np.linalg.norm(kp.pt-pt0) for kp in KPlist]
idx = np.argmin(norms)
KPlist0.append( KPlist[idx] )
# print(KPlist[idx].pt, pt0, len(imas_kps.GetSimulatedKPs(np.flip(pt0))) )
KPlist = KPlist0
h, w = img.shape[:2]
img1, mask1, A1, Ai1 = SimulateAffineMap(im1_zoom, im1_phi2, im1_t, im1_phi1, img)
KPlist1 = ComputeSIFTKeypoints(img1)
KPlist1, temp = Filter_Affine_In_Rect(KPlist1,A1,[0,0],[w,h])
KPlist1_affine = AffineKPcoor(KPlist1,Ai1)
img2, mask2, A2, Ai2 = SimulateAffineMap(im2_zoom, im2_phi2, im2_t, im2_phi1, img)
KPlist2 = ComputeSIFTKeypoints(img2)
KPlist2, temp = Filter_Affine_In_Rect(KPlist2,A2,[0,0],[w,h])
KPlist2_affine = AffineKPcoor(KPlist2,Ai2)
if len(KPlist1_affine)==0 or len(KPlist2_affine)==0:
continue
for i in np.random.permutation( range(0,len(KPlist)) ):
idx1 = FilterKPsinList(KPlist[i], KPlist1_affine)
idx2 = FilterKPsinList(KPlist[i], KPlist2_affine)
if self.OutputNegativePatch:
idxN = random.randint(0,len(KPlist2)-1)
oN, lN, sN = unpackSIFTOctave(KPlist2[idxN])
else:
idxN = None
sidx1, sidx2 = FindBestKPinLists( im1_zoom, im2_zoom, [KPlist1_affine[i] for i in idx1],[KPlist2_affine[i] for i in idx2])
if np.size(idx1)>0 and np.size(idx2)>0 and sidx1 !=None and sidx2 !=None and (self.OutputNegativePatch==False or idxN!=None):
idx1 = idx1[sidx1:sidx1+1]
idx2 = idx2[sidx2:sidx2+1]
o, l, s = unpackSIFTOctave(KPlist1[idx1[0]])
pyr1 = buildGaussianPyramid( img1, o+2 )
o, l, s = unpackSIFTOctave(KPlist2[idx2[0]])
if self.OutputNegativePatch:
o = np.max([o,oN])
pyr2 = buildGaussianPyramid( img2, o+2 )
patches1, A_list1, Ai_list1 = ComputePatches(KPlist1[idx1[0]:idx1[0]+1],pyr1)
patches2, A_list2, Ai_list2 = ComputePatches(KPlist2[idx2[0]:idx2[0]+1],pyr2)
hs, ws = patches1[0].shape[:2]
p = np.zeros((hs, ws), np.uint8)
p[:] = 1
AS1 = ComposeAffineMaps(A_list1[0],A1)
AS2 = ComposeAffineMaps(A_list2[0],A2)
ASi1 = ComposeAffineMaps(Ai1,Ai_list1[0])
ASi2 = ComposeAffineMaps(Ai2,Ai_list2[0])
A_from_1_to_2 = ComposeAffineMaps(AS2,ASi1)
A_from_2_to_1 = ComposeAffineMaps(AS1,ASi2)
kp_sq = SquareOrderedPts(hs,ws)
kp_sq1 = AffineKPcoor(kp_sq,A_from_2_to_1)
kp_sq2 = AffineKPcoor(kp_sq,A_from_1_to_2)
kpin1 = [pt for k in kp_sq1 for pt in k.pt]
kpin2 = [pt for k in kp_sq2 for pt in k.pt]
stamp = str(time.time())+'.'+ str(np.random.randint(0,9999))
cv2.imwrite(self.save_path+"/"+stamp+".p1.png",patches1[0])
cv2.imwrite(self.save_path+"/"+stamp+".p2.png",patches2[0])
np.savetxt(self.save_path+"/"+stamp+".vector.txt", np.concatenate((kpin1,kpin2)))
if self.OutputNegativePatch:
patchesN, A_listN, Ai_listN = ComputePatches([KPlist2[idxN]],pyr2)
ASN = ComposeAffineMaps(A_listN[0],A2)
ASiN = ComposeAffineMaps(Ai2,Ai_listN[0])
A_from_1_to_N = ComposeAffineMaps(ASN,ASi1)
A_from_N_to_1 = ComposeAffineMaps(AS1,ASiN)
kp_sq1 = AffineKPcoor(kp_sq,A_from_N_to_1)
kp_sq2 = AffineKPcoor(kp_sq,A_from_1_to_N)
kpin1N = [pt for k in kp_sq1 for pt in k.pt]
kpin2N = [pt for k in kp_sq2 for pt in k.pt]
cv2.imwrite(self.save_path+"/"+stamp+".pN.png",patchesN[0])
np.savetxt(self.save_path+"/"+stamp+".vectorN.txt", np.concatenate((kpin1N,kpin2N)))
if AllOutput:
return np.dstack((patches1[0]/self.imgdivfactor, patches2[0]/self.imgdivfactor, patchesN[0]/self.imgdivfactor)), self.NormalizeVector(np.concatenate((kpin1,kpin2))), self.NormalizeVector(np.concatenate((kpin1N,kpin2N)))
else:
return np.dstack((patches1[0]/self.imgdivfactor, patches2[0]/self.imgdivfactor, patchesN[0]/self.imgdivfactor)), self.NormalizeVector(np.concatenate((kpin1,kpin2)))
else:
# to retreive info do:
# np.concatenate((kpin1,kpin2)) = np.loadtxt(self.save_path+"/"+stamp+".vector.txt")
return np.dstack((patches1[0]/self.imgdivfactor, patches2[0]/self.imgdivfactor)), self.NormalizeVector(np.concatenate((kpin1,kpin2)))
def SimulateAffineMap(zoom_step,psi,t1_step,phi,img0,mask=None, CenteredAt=None, t2_step = 1.0, inter_flag = cv2.INTER_CUBIC, border_flag = cv2.BORDER_CONSTANT, SimuBlur = True):
'''
Computing affine deformations of images as in [https://rdguez-mariano.github.io/pages/imas]
Let A = R_psi0 * diag(t1,t2) * R_phi0 with t1>t2
= lambda * R_psi0 * diag(t1/t2,1) * R_phi0
Parameters given should be as:
zoom_step = 1/lambda
t1_step = 1/t1
t2_step = 1/t2
psi = -psi0 (in degrees)
phi = -phi0 (in degrees)
ASIFT proposed params:
inter_flag = cv2.INTER_LINEAR
SimuBlur = True
Also, another kind of exterior could be:
border_flag = cv2.BORDER_REPLICATE
'''
tx = zoom_step*t1_step
ty = zoom_step*t2_step
assert tx>=1 and ty>=1, 'Either scale or t are defining a zoom-in operation. If you want to zoom-in do it manually. tx = '+str(tx)+', ty = '+str(ty)
img = img0.copy()
arr = []
DoCenter = False
if type(CenteredAt) is list:
DoCenter = True
arr = np.array(CenteredAt).reshape(-1,2)
h, w = img.shape[:2]
tcorners = SquareOrderedPts(h,w,CV=False)
if mask is None:
mask = np.zeros((h, w), np.uint8)
mask[:] = 255
A1 = np.float32([[1, 0, 0], [0, 1, 0]])
if phi != 0.0:
phi = np.deg2rad(phi)
s, c = np.sin(phi), np.cos(phi)
A1 = np.float32([[c,-s], [ s, c]])
tcorners = np.dot(tcorners, A1.T)
x, y, w, h = cv2.boundingRect(np.int32(tcorners).reshape(1,-1,2))
A1 = np.hstack([A1, [[-x], [-y]]])
if DoCenter and tx == 1.0 and ty == 1.0 and psi == 0.0:
arr = AffineArrayCoor(arr,A1)[0].ravel()
h0, w0 = img0.shape[:2]
A1[0][2] += h0/2.0 - arr[0]
A1[1][2] += w0/2.0 - arr[1]
w, h = w0, h0
img = cv2.warpAffine(img, A1, (w, h), flags=inter_flag, borderMode=border_flag)
else:
img = cv2.warpAffine(img, A1, (w, h), flags=inter_flag, borderMode=border_flag)
h, w = img.shape[:2]
A2 = np.float32([[1, 0, 0], [0, 1, 0]])
tcorners = SquareOrderedPts(h,w,CV=False)
if tx != 1.0 or ty != 1.0:
sx = 0.8*np.sqrt(tx*tx-1)
sy = 0.8*np.sqrt(ty*ty-1)
if SimuBlur:
img = cv2.GaussianBlur(img, (0, 0), sigmaX=sx, sigmaY=sy)
A2[0] /= tx
A2[1] /= ty
if psi != 0.0:
psi = np.deg2rad(psi)
s, c = np.sin(psi), np.cos(psi)
Apsi = np.float32([[c,-s], [ s, c]])
Apsi = np.matmul(Apsi,A2[0:2,0:2])
tcorners = np.dot(tcorners, Apsi.T)
x, y, w, h = cv2.boundingRect(np.int32(tcorners).reshape(1,-1,2))
A2[0:2,0:2] = Apsi
A2[0][2] -= x
A2[1][2] -= y
if tx != 1.0 or ty != 1.0 or psi != 0.0:
if DoCenter:
A = ComposeAffineMaps(A2,A1)
arr = AffineArrayCoor(arr,A)[0].ravel()
h0, w0 = img0.shape[:2]
A2[0][2] += h0/2.0 - arr[0]
A2[1][2] += w0/2.0 - arr[1]
w, h = w0, h0
img = cv2.warpAffine(img, A2, (w, h), flags=inter_flag, borderMode=border_flag)
A = ComposeAffineMaps(A2,A1)
if psi!=0 or phi != 0.0 or tx != 1.0 or ty != 1.0:
if DoCenter:
h, w = img0.shape[:2]
else:
h, w = img.shape[:2]
mask = cv2.warpAffine(mask, A, (w, h), flags=inter_flag)
Ai = cv2.invertAffineTransform(A)
return img, mask, A, Ai
def unpackSIFTOctave(kp, XI=False):
''' Opencv packs the true octave, scale and layer inside kp.octave.
This function computes the unpacking of that information.
'''
_octave = kp.octave
octave = _octave&0xFF
layer = (_octave>>8)&0xFF
if octave>=128:
octave |= -128
if octave>=0:
scale = float(1/(1<<octave))
else:
scale = float(1<<-octave)
if XI:
yi = (_octave>>16)&0xFF
xi = yi/255.0 - 0.5
return octave, layer, scale, xi
else:
return octave, layer, scale
def packSIFTOctave(octave, layer, xi=0.0):
po = octave&0xFF
pl = (layer&0xFF)<<8
pxi = round((xi + 0.5)*255.0)&0xFF
pxi = pxi<<16
return po + pl + pxi
def DescRadius(kp, InPyr=False, SIFT=False):
''' Computes the Descriptor radius with respect to either an image
in the pyramid or to the original image.
'''
factor = siftparams.new_radius_descr
if SIFT:
factor = siftparams.lambda_descr
if InPyr:
o, l, s = unpackSIFTOctave(kp)
return( np.float32(kp.size*s*factor*0.5) )
else:
return( np.float32(kp.size*factor*0.5) )
def AngleDiff(a,b, InRad=False):
''' Computes the Angle Difference between a and b.
0<=a,b<=360
'''
if InRad:
a = np.rad2deg(a) % 360
b = np.rad2deg(b) % 360
assert a>=0 and a<=360 and b>=0 and b<=360, 'a = '+str(a)+', b = '+str(b)
anglediff = abs(a-b)% 360
if anglediff > 180:
anglediff = 360 - anglediff
if InRad:
return np.deg2rad(anglediff)
else:
return anglediff
def FilterKPsinList(kp0,kp_list,maxdist = MaxSameKP_dist, maxangle = MaxSameKP_angle):
''' Filters out all keypoints in kp_list having angle differences and distances above some thresholds.
Those comparisons should be made with restpect to the groundtruth image.
'''
idx = () # void tuple
for i in range(0,np.size(kp_list)):
dist = cv2.norm(kp0.pt,kp_list[i].pt)
anglediff = AngleDiff( kp0.angle , kp_list[i].angle )
if dist<maxdist and anglediff<maxangle:
idx += tuple([i])
return idx
def FilterOutUselessKPs(kplist,patches, TensorThres = 10.0):
''' The Structure Tensor is used here to filter out unidimensional patches, i.e,
patches for which there is only information in one dimension.
For that we demand l_max / l_min less than a threshold (where l_i are
the eigenvalues of the structure matrix)
In practice if A = k B, A*B = k B^2
(A + B)^2 = (k+1)^2 * B^2
k B^2 > t * (k+1)^2 * B^2 sii k / (k+1)^2 > t
This is a decreasing function for k > 1 and value 0.3 at k=1.
f(k) = k / (k+1)^2
Setting t = 0.08, means k<=10
'''
tensor_thres = TensorThres / pow( 1 + TensorThres ,2)
rkplist, rpatches = [], []
for n in range(len(kplist)):
dx = cv2.Sobel(patches[n],cv2.CV_64F,1,0,ksize = 1)
dy = cv2.Sobel(patches[n],cv2.CV_64F,0,1,ksize = 1)
ts_xy = (dx*dy).sum()
ts_xx = (dx*dx).sum()
ts_yy = (dy*dy).sum()
det = ts_xx * ts_yy - ts_xy * ts_xy # \prod l_i
trace = ts_xx + ts_yy # \sum l_i
if ((det > tensor_thres * trace * trace)):
rkplist.append(kplist[n])
rpatches.append(patches[n])
# print(len(kplist),len(rkplist))
return rkplist, rpatches
def FindBestKPinLists(lambda1,lambda2, kp_list1, kp_list2):
''' Finds the best pair (i,j) such that kp_list1[i] equals kp_list2[j] in
the groundtruth image. The groundtruth image was zoom-out by a factor lambda1
for the image corresponding to kp_list1, and same goes for lambda2 and kp_list2.
'''
idx1 = None
idx2 = None
mindist = MaxSameKP_dist
mindiffsizes = 10.0
for i in range(0,np.size(kp_list1)):
kp1 = kp_list1[i]
size1 = DescRadius(kp1)*lambda1
for j in range(0,np.size(kp_list2)):
kp2 = kp_list2[j]
size2 = DescRadius(kp2)*lambda2
dist = cv2.norm(kp1.pt,kp2.pt)
diffsizes = abs(size1 - size2)
if diffsizes<mindiffsizes or (dist<mindist and diffsizes==mindiffsizes) :
mindist = dist
mindiffsizes = diffsizes
# print(size1, size2, diffsizes)
idx1 = i
idx2 = j
return idx1, idx2
def features_deepcopy(f):
return [cv2.KeyPoint(x = k.pt[0], y = k.pt[1],
_size = k.size, _angle = k.angle,
_response = k.response, _octave = k.octave,
_class_id = k.class_id) for k in f]
def matches_deepcopy(f):
return [cv2.DMatch(_queryIdx=k.queryIdx, _trainIdx=k.trainIdx, _distance=k.distance) for k in f]
def Filter_Affine_In_Rect(kp_list, A, p_min, p_max, desc_list = None, isSIFT=False):
''' Filters out all descriptors in kp_list that do not lay inside the
the parallelogram defined by the image of a rectangle by the affine transform A.
The rectangle is defined by (p_min,p_max).
'''
desc_listing = False
desc_list_in = []
desc_pos = 0
if type(desc_list) is np.ndarray:
desc_listing = True
desc_list_in = desc_list.copy()
x1, y1 = p_min[:2]
x2, y2 = p_max[:2]
Ai = cv2.invertAffineTransform(A)
kp_back = AffineKPcoor(kp_list,Ai)
kp_list_in = []
kp_list_out = []
cyclic_corners = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2], [x1, y1]])
cyclic_corners = AffineArrayCoor(cyclic_corners,A)
for i in range(0,np.size(kp_back)):
if kp_back[i].pt[0]>=x1 and kp_back[i].pt[0]<x2 and kp_back[i].pt[1]>=y1 and kp_back[i].pt[1]<y2:
In = True
r = DescRadius(kp_list[i],SIFT=isSIFT)*1.4142
for j in range(0,4):
if r > dist_pt_to_line(kp_list[i].pt,cyclic_corners[j],cyclic_corners[j+1]):
In = False
if In == True:
if desc_listing:
desc_list_in[desc_pos,:]= desc_list[i,:]
desc_pos +=1
kp_list_in.append(kp_list[i])
else:
kp_list_out.append(kp_list[i])
else:
kp_list_out.append(kp_list[i])
if desc_listing:
return kp_list_in, desc_list_in[:desc_pos,:], kp_list_out
else:
return kp_list_in, kp_list_out
def dist_pt_to_line(p,p1,p2):
''' Computes the distance of a point (p) to a line defined by two points (p1, p2). '''
x0, y0 = np.float32(p[:2])
x1, y1 = np.float32(p1[:2])
x2, y2 = np.float32(p2[:2])
dist = abs( (y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1 ) / np.sqrt( pow(y2-y1,2) + pow(x2-x1,2) )
return dist
def PolarCoor_from_vector(p_source,p_arrow):
''' It computes the \rho and \theta such that
\rho * exp( i * \theta ) = p_arrow-p_source
'''
p = np.array(p_arrow)- np.array(p_source)
rho = np.linalg.norm(p)
theta = 0
if rho>0:
theta = np.arctan2(p[1],p[0])
theta = np.rad2deg(theta % (2 * np.pi))
return rho, theta
def ComposeAffineMaps(A_lhs,A_rhs):
''' Comutes the composition of affine maps:
A = A_lhs ∘ A_rhs
'''
A = np.matmul(A_lhs[0:2,0:2],A_rhs)
A[:,2] += A_lhs[:,2]
return A
def kp2LocalAffine(kp, w=siftparams.new_radius_descr*2+1,h=siftparams.new_radius_descr*2+1):
''' Computes the affine map A such that: for any x
living in the image coordinates A(x) is the
corresponding coordinates of x in the patch computed
from the keypoint kp.
'''
scale = siftparams.new_radius_descr/DescRadius(kp)
x, y= kp.pt[0], kp.pt[1]
angle = 360.0 - kp.angle
if(np.abs(angle - 360.0) < siftparams.flt_epsilon):
angle = 0.0
phi = np.deg2rad(angle)
s, c = np.sin(phi), np.cos(phi)
R = np.float32([[c,-s], [ s, c]])
A = scale * np.float32([[1, 0, -x], [0, 1, -y]])
A = np.matmul(R,A)
A[:,2] += np.array([w/2, h/2])
return A
def AffineArrayCoor(arr,A):
if type(arr) is list:
arr = np.array(arr).reshape(-1,2)
AA = A[0:2,0:2]
Ab = A[:,2]
arr_out = []
for j in range(0,arr.shape[0]):
arr_out.append(np.matmul(AA,np.array(arr[j,:])) + Ab )
return np.array(arr_out)
def AffineKPcoor(kp_list,A, Pt_mod = True, Angle_mod = True):
''' Transforms information details on each kp_list keypoints by following
the affine map A.
'''
kp_affine = features_deepcopy(kp_list)
AA = A[0:2,0:2]
Ab = A[:,2]
for j in range(0,np.size(kp_affine)):
newpt = tuple( np.matmul(AA,np.array(kp_list[j].pt)) + Ab)
if Pt_mod:
kp_affine[j].pt = newpt
if Angle_mod:
phi = np.deg2rad(kp_list[j].angle)
s, c = np.sin(phi), np.cos(phi)
R = np.float32([[c,-s], [ s, c]])
p_arrow = np.matmul( R , [50.0, 0.0] ) + np.array(kp_list[j].pt)
p_arrow = tuple( np.matmul(AA,p_arrow) + Ab)
rho, kp_affine[j].angle = PolarCoor_from_vector(newpt, p_arrow)
return kp_affine
def ProposeOpticallyOverlapedPatches(P1,A_p1_to_p2,P2, w=siftparams.new_radius_descr*2+1,h=siftparams.new_radius_descr*2+1):
A = cv2.invertAffineTransform(A_p1_to_p2)
Avec = affine_decomp(A)
Ai = A_p1_to_p2
Aivec = affine_decomp(Ai)
center = [h/2.0, w/2.0]
t1 = Avec[0]*Avec[2]
t2 = Avec[0]
if t1>=1 and t2>=1: # Only Patch 1 loose information
lambdastar = 1.0
prop_p2, mask2, sA2, sAi2 = SimulateAffineMap(lambdastar,0.0,1.0,0.0,P2,mask=None,CenteredAt=center)
center = list( AffineArrayCoor(center,A).ravel() )
prop_p1, mask1, sA1, sAi1 = SimulateAffineMap(lambdastar*Avec[0],-np.rad2deg(Aivec[1]),1.0,-np.rad2deg(Aivec[3]),P1,mask=None,CenteredAt=center,t2_step = Aivec[2])
# Why the above line is really computing A^-1 ?
# Read the following:
# Let A = R_phi * diag(t1,t2) * R_psi =
# = t2 * R_phi * diag(t1/t2,1) * R_psi
# which implies A^-1 = 1/t1 * R_(-pi/2-psi) * diag(t1/t2) * R_(pi/2 - phi)
# So
# t1_step_{A^-1} = 1/t1_{A^-1} = t2
# t2_step_{A^-1} = 1/t2_{A^-1} = t1
# So, as Avec[0] = t2,
# t2*diag(1,t1/t2) = diag(t2,t1) = diag(t1_step_{A^-1}, t2_step_{A^-1})
elif t1<1 and t2<1: # Only Patch 2 loose information
lambdastar = 1.0
prop_p1, mask1, sA1, sAi1 = SimulateAffineMap(lambdastar,0.0,1.0,0.0,P1,mask=None,CenteredAt=center)
center = list( AffineArrayCoor(center,Ai).ravel() )
prop_p2, mask2, sA2, sAi2 = SimulateAffineMap(lambdastar*Aivec[0],-np.rad2deg(Avec[1]),1.0,-np.rad2deg(Avec[3]),P2,mask=None,CenteredAt=center,t2_step = Avec[2])
else: # Both Patches loose information
if t2 < 1.0/t1: # Avec[0] < Aivec[0]
lambdastar = 1.0/Avec[0] + 0.000001
prop_p1, mask1, sA1, sAi1 = SimulateAffineMap(lambdastar,0.0,1.0,0.0,P1,mask=None,CenteredAt=center)
center = list( AffineArrayCoor(center,Ai).ravel() )
prop_p2, mask2, sA2, sAi2 = SimulateAffineMap(lambdastar*Aivec[0],-np.rad2deg(Avec[1]),1.0,-np.rad2deg(Avec[3]),P2,mask=None,CenteredAt=center,t2_step = Avec[2])
else:
lambdastar = 1.0/Aivec[0] + 0.000001
prop_p2, mask2, sA2, sAi2 = SimulateAffineMap(lambdastar,0.0,1.0,0.0,P2,mask=None,CenteredAt=center)
center = list( AffineArrayCoor(center,A).ravel() )
prop_p1, mask1, sA1, sAi1 = SimulateAffineMap(lambdastar*Avec[0],-np.rad2deg(Aivec[1]),1.0,-np.rad2deg(Aivec[3]),P1,mask=None,CenteredAt=center,t2_step = Aivec[2])
prop_p1[prop_p1<0] = 0
prop_p1[prop_p1>255] = 255
prop_p2[prop_p2<0] = 0
prop_p2[prop_p2>255] = 255
mask = mask1*mask2
return prop_p1, prop_p2, mask
def affine_decomp2affine(vec):
lambda_scale = vec[0]
phi2 = vec[1]
t = vec[2]
phi1 = vec[3]
s, c = np.sin(phi1), np.cos(phi1)
R_phi1 = np.float32([[c,s], [ -s, c]])
s, c = np.sin(phi2), np.cos(phi2)
R_phi2 = np.float32([[c,s], [ -s, c]])
A = lambda_scale * np.matmul(R_phi2, np.matmul(np.diag([t,1.0]),R_phi1) )
if np.shape(vec)[0]==6:
A = np.concatenate(( A, [[vec[4]], [vec[5]]] ), axis=1)
return A
def affine_decomp(A0,doAssert=True, ModRots=False):
'''Decomposition of a 2x2 matrix A (whose det(A)>0) satisfying
A = lambda*R_phi2*diag(t,1)*R_phi1.
where lambda and t are scalars, and R_phi1, R_phi2 are rotations.
'''
epsilon = 0.0001
A = A0[0:2,0:2]
Adet = np.linalg.det(A)
if doAssert:
assert Adet>0
if Adet>0:
# A = U * np.diag(s) * V
U, s, V = np.linalg.svd(A, full_matrices=True)
T = np.diag(s)
K = np.float32([[-1, 0], [0, 1]])
# K*D*K = D
if ((np.linalg.norm(np.linalg.det(U)+1)<=epsilon) and (np.linalg.norm(np.linalg.det(V)+1)<=epsilon)):
U = np.matmul(U,K)
V = np.matmul(K,V)
phi2_drift = 0.0
# Computing First Rotation
phi1 = np.arctan2( V[0,1], V[0,0] )
if ModRots and phi1<0:
phi1 = phi1 + np.pi
phi2_drift = -np.pi
# Computing Second Rotation
phi2 = np.mod( np.arctan2( U[0,1],U[0,0]) + phi2_drift , 2.0*np.pi)
# Computing Tilt and Lambda
lambda_scale = T[1,1]
T[0,0]=T[0,0]/T[1,1]
T[1,1]=1.0
if T[0,0]-1.0<=epsilon:
phi2 = np.mod(phi1+phi2,2.0*np.pi)
phi1 = 0.0
s, c = np.sin(phi1), np.cos(phi1)
R_phi1 = np.float32([[c,s], [ -s, c]])
s, c = np.sin(phi2), np.cos(phi2)
R_phi2 = np.float32([[c,s], [ -s, c]])
temp = lambda_scale*np.matmul( R_phi2 ,np.matmul(T,R_phi1) )
# Couldnt decompose A
if doAssert and np.linalg.norm(A - temp,'fro')>epsilon:
print('Error: affine_decomp couldnt really decompose A')
print(A0)
print('----- end of A')
rvec = [lambda_scale, phi2, T[0,0], phi1]
if np.shape(A0)[1]==3:
rvec = np.concatenate(( rvec, [A0[0,2], A0[1,2]] ))
else:
rvec = [1.0, 0.0, 1.0, 0.0, 0.0, 0.0]
return rvec
def transition_tilt( Avec, Bvec ):
''' Computes the transition tilt between two affine maps as in [https://rdguez-mariano.github.io/pages/imas]
Let
A = lambda1 * R_phi1 * diag(t,1) * psi1
B = lambda2 * R_phi2 * diag(s,1) * psi2
then Avec and Bvec are respectively the affine_decomp of A and B
'''
t = Avec[2]
psi1 = Avec[3]
s = Bvec[2]
psi2 = Bvec[3]
cos_2 = pow( np.cos(psi1-psi2), 2.0)
g = ( pow(t/s, 2.0) + 1.0 )*cos_2 + ( 1.0/pow(s, 2.0) + pow(t,2.0) )*( 1.0 - cos_2 )
G = (s/t)*g/2.0
tau = G + np.sqrt( pow(G,2.0) - 1.0 )
return tau
tilts_1_25 = [1.0, np.pi, 1.34982, 0.790026, 1.69436, 0.395013] # covers a region=1.71 with disks radius of 1.25
tilts_1_15 = [1.0, np.pi, 1.26938, 0.524565, 1.43195, 0.349323, 1.68408, 0.243276] # covers a region=1.708 disks with radius of 1.15
tilts_1_7 = [1.0, np.pi, 2.6175699234, 0.3980320096, 5.1816802025, 0.1983139962]
tilts_1_4 = [1.0, np.pi, 1.7745000124, 0.5254489779, 2.3880701065, 0.2863940001, 3.9156799316, 0.1429599971]
tilts_2 = [1.0, np.pi, 3.33005, 0.455102]
def GetCovering(coveringcode, endAngle=np.pi):
covering=tuple([])
for i in range(int(len(coveringcode)/2)):
covering = covering + tuple([[1.0, 0.0, coveringcode[2*i], x, 0.0, 0.0] for x in np.arange(0.0, endAngle, coveringcode[2*i+1])])
return covering
def SelectSimusFromData(A_decomp_list, simu_decomp_list=None, tilt_radius=np.log(1.7), thres=-1.0, Depict=True ):
res = []
if simu_decomp_list is None:
Adecomp_list = np.array(A_decomp_list).copy()
while len(Adecomp_list)>0 and len(Adecomp_list)>len(A_decomp_list)*thres:
BestScore = 0
BestAnnears, BestA = [], []
for A in Adecomp_list:
Annears = np.array([transition_tilt(A,B) for B in Adecomp_list])>np.exp(tilt_radius)
Ascore = len(Annears) - np.sum(Annears)
if Ascore>BestScore:
BestA = A
BestScore = Ascore
BestAnnears = Annears
Adecomp_list = Adecomp_list[BestAnnears]
res.append(BestA)
else:
for s in simu_decomp_list:
count = 0
for a in A_decomp_list:
if transition_tilt(s, a)<np.exp(tilt_radius):
count=count+1
if float(count/len(A_decomp_list))>thres:
res.append(s)
return res
class IMAS_keypoints(object):
def __init__(self, img):
self.img = img
self.SIFTAID = False
# all-in indexed
self.kplist = []
self.desc = []
self.simu_idx = []
# Idexed by simus
self.kplists = []
self.descs = []
self.patches = []
self.tilts = []
self.pyrs = []
self.A_orig_to_simu = []
self.simu2orig_detected = []
self.imasdetected = np.zeros(np.shape(self.img), dtype=np.float32)
self.imasdetected_idxs = [[] for _ in range(np.shape(img)[0]*np.shape(img)[1])]
self.A_simu_to_orig = []
self.in_all_idx = []
self.masks = []
self.imgs = []
def GetSimulatedKPs(self,idx):
''' idx is of type point from cv2 then call as
GetSimulatedKPs( np.flip( kp.pt ) )
'''
if np.shape(idx)==():
x, y = np.unravel_index(idx, self.imasdetected.shape)
idx = np.ravel_multi_index([x,y], self.img.shape)
else:
x, y = idx
idx = np.ravel_multi_index([x,y], self.img.shape)
simulated_kps = []