-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPatternLocalisation.lua
1344 lines (1147 loc) · 45.2 KB
/
PatternLocalisation.lua
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
--[[
PatternLocalisation.lua
Copyright (c) 2018, Xamla and/or its affiliates. All rights reserved.
This program 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 2
of the License, or any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
local cv = require "cv"
cv.flann = require "cv.flann"
require "cv.highgui"
require "cv.videoio"
require "cv.imgproc"
require "cv.calib3d"
require "cv.imgcodecs"
require "cv.features2d"
local autocal = require 'auto_calibration.env'
local PatternLocalisation = torch.class("PatternLocalisation", autocal)
function PatternLocalisation:__init()
self.patDictData = {}
self.pattern = {}
self.pattern.width = 1
self.pattern.height = 1
self.pattern.pointDist = 0
self.colorTab = { -- list of colors for visualisation
{255,0,0}, {255,170,0}, {95,204,41}, {0,102,153}, {180,61,204}, {204,0,0}, {153,102,0}, {42,255,0}, {0,127,255}, {255,0,255},
{255,128,128}, {255,204,102}, {0,153,51}, {0,77,153}, {153,0,128}, {255,106,77}, {255,213,0}, {0,255,128}, {0,85,255}, {255,102,229},
{153,77,61}, {153,128,0}, {61,204,133}, {0,51,153}, {255,0,170}, {255,85,0}, {255,255,0}, {0,255,212}, {102,136,204}, {153,77,128},
{153,51,0}, {255,255,128}, {0,153,128}, {0,0,255}, {153,0,77}, {255,153,102}, {153,153,77}, {0,255,255}, {0,0,204}, {255,128,191},
{255,128,0}, {173,204,20}, {0,204,204}, {153,102,255}, {255,0,85}, {153,77,0}, {170,255,0}, {0,213,255}, {170,0,255}, {255,77,136},
{255,179,102}, {112,153,31}, {0,128,153}, {102,0,153}, {153,0,26}, {153,115,77}, {191,255,128}, {0,170,255}, {122,61,153}, {153,77,89}
}
self:generateDefaultCircleFinderParams()
self.camIntrinsics = nil
self.stereoCalibration = nil
self.debugParams = {
circleSearch = false,
clustering = false,
pose = false
}
-- parameters for DBScan
self.DBScanEps = 80 -- defines the size of the point neighbourhood
self.DBScanMinPts = 6 -- minimum number of points required to form a dense region
-- constants, used by DBScan
self.clusterStatus = {
kUnprocessed = 0,
kProcessed = 1,
kNoise = 2,
kAssigned = 4
}
-- rescaling factor for visualisation
self.imgShowRescale = 0.5
end
function PatternLocalisation:setDBScanParams(eps, minPts)
self.DBScanEps = eps
self.DBScanMinPts = minPts
end
function PatternLocalisation:setPatternData(width, height, pointDist)
self.pattern.width = width
self.pattern.height = height
self.pattern.pointDist = pointDist
end
function PatternLocalisation:setPatternIDdictionary(dict)
self.patDictData = dict
end
function PatternLocalisation:setCamIntrinsics(camCalib)
self.camIntrinsics = camCalib
end
function PatternLocalisation:setStereoCalibration(stereoCalib)
self.stereoCalibration = stereoCalib
end
function PatternLocalisation:generateDefaultCircleFinderParams()
self.circleFinderParams = cv.SimpleBlobDetector_Params {}
self.circleFinderParams.thresholdStep = 5
self.circleFinderParams.minThreshold = 10
self.circleFinderParams.maxThreshold = 230
self.circleFinderParams.minRepeatability = 3
self.circleFinderParams.minDistBetweenBlobs = 5
self.circleFinderParams.filterByColor = false
self.circleFinderParams.blobColor = 0
self.circleFinderParams.filterByArea = true -- area of the circle in pixels
self.circleFinderParams.minArea = 200
self.circleFinderParams.maxArea = 1000
self.circleFinderParams.filterByCircularity = true
self.circleFinderParams.minCircularity = 0.6
self.circleFinderParams.maxCircularity = 10
self.circleFinderParams.filterByInertia = false
self.circleFinderParams.minInertiaRatio = 0.6
self.circleFinderParams.maxInertiaRatio = 10
self.circleFinderParams.filterByConvexity = true
self.circleFinderParams.minConvexity = 0.8
self.circleFinderParams.maxConvexity = 10
end
function PatternLocalisation:plotCrosshair(img, posX, posY, crossSize)
local irSize = {x = img:size()[2], y = img:size()[1]} -- to get x, y img size
local lineLength = crossSize or 6
local centerX = posX
local centerY = posY
cv.line {
img,
{(centerX) - 2, (centerY)},
{(centerX) - 2 - lineLength, (centerY)},
{0, 0, 0}
}
cv.line {
img,
{(centerX) + 2, (centerY)},
{(centerX) + 2 + lineLength, (centerY)},
{0, 0, 0}
}
cv.line {
img,
{(centerX), (centerY) - 2},
{(centerX), (centerY) - 2 - lineLength},
{0, 0, 0}
}
cv.line {
img,
{(centerX), (centerY) + 2},
{(centerX), (centerY) + 2 + lineLength},
{0, 0, 0}
}
for i = -1, 1, 2 do
cv.line {
img,
{(centerX) - 4, (centerY) + i},
{(centerX) - 2 - lineLength, (centerY) + i},
{250, 200, 200}
}
cv.line {
img,
{(centerX) + 4, (centerY) + i},
{(centerX) + 2 + lineLength, (centerY) + i},
{250, 200, 200}
}
cv.line {
img,
{(centerX) + i, (centerY) - 4},
{(centerX) + i, (centerY) - 2 - lineLength},
{250, 200, 200}
}
cv.line {
img,
{(centerX) + i, (centerY) + 4},
{(centerX) + i, (centerY) + 2 + lineLength},
{250, 200, 200}
}
end
end
-- Generate ground truth circle center points of the calibration pattern.
-- Z is set to 0 for all points.
function PatternLocalisation:generatePatternPoints(pointsX, pointsY, pointSize)
-- calculates the groundtruth x, y, z positions of the points of the asymmetric circle pattern
local corners = torch.FloatTensor(pointsX * pointsY, 1, 3):zero()
local i = 1
for y = 1, pointsY do
for x = 1, pointsX do
corners[i][1][1] = (2 * (x - 1) + (y - 1) % 2) * pointSize
corners[i][1][2] = (y - 1) * pointSize
corners[i][1][3] = 0
i = i + 1
end
end
return corners
end
function PatternLocalisation:rotVectorToMat3x3(vec)
-- transform a rotation vector as e.g. provided by solvePnP to a 3x3 rotation matrix using the Rodrigues' rotation formula
local theta = torch.norm(vec)
local r = vec / theta
r = torch.squeeze(r)
local mat = torch.Tensor({{0, -1 * r[3], r[2]}, {r[3], 0, -1 * r[1]}, {-1 * r[2], r[1], 0}})
r = r:resize(3, 1)
return torch.eye(3) * math.cos(theta) + (r * r:t()) * (1 - math.cos(theta)) + mat * math.sin(theta)
end
function PatternLocalisation:mirrorPatternPoints(points, patWidth, patHeight, imgDebug)
-- resort points
local pointsResorted = torch.FloatTensor(patWidth * patHeight, 1, 2)
for col = 0, patHeight - 1 do
for row = 0, patWidth - 1 do
pointsResorted[col * patWidth + row + 1][1][{}] =
points[(patWidth) * (patHeight - col) - patWidth + row + 1][1][{}]
end
end
if imgDebug ~= nil then
for i = 1, patWidth * patHeight do
self:plotCrosshair(imgDebug, pointsResorted[i][1][1], pointsResorted[i][1][2], 8)
print("point " .. pointsResorted[i][1][1] .. ", y=" .. pointsResorted[i][1][2])
cv.imshow {"debug", imgDebug}
cv.waitKey {1000}
end
end
return pointsResorted
end
local function findMarker(markerList, markerId)
for i,m in ipairs(markerList) do
if m.id == markerId then
return m
end
end
return nil
end
function PatternLocalisation:calcCamPose_original(inputImg, camIntrinsics, patternData, doDebug, imgShowInput)
doDebug = doDebug or false
local camPoseFinal
local blobDetector = cv.SimpleBlobDetector {self.circleFinderParams}
local found, points =
cv.findCirclesGrid {
image = inputImg,
patternSize = {height = patternData.height, width = patternData.width},
flags = cv.CALIB_CB_ASYMMETRIC_GRID + cv.CALIB_CB_CLUSTERING,
blobDetector = blobDetector
}
if found then
local points3d = self:generatePatternPoints(patternData.width, patternData.height, patternData.pointDist)
local poseFound, poseCamRotVector, poseCamTrans =
cv.solvePnP {
objectPoints = points3d,
imagePoints = points,
cameraMatrix = camIntrinsics,
distCoeffs = torch.DoubleTensor(1, 5):zero()
}
local poseCamRotMatrix = self:rotVectorToMat3x3(poseCamRotVector)
camPoseFinal = torch.DoubleTensor(4, 4):zero()
camPoseFinal[{{1, 3}, {1, 3}}] = poseCamRotMatrix
camPoseFinal[{{1, 3}, {4}}] = poseCamTrans
camPoseFinal[4][4] = 1
end
if doDebug then
local imgShow
if imgShowInput ~= nil then
imgShow = imgShowInput
else
imgShow = self:grayToRGB(inputImg)
end
if found then
cv.drawChessboardCorners {image = imgShow, patternSize = pattern, corners = points, patternWasFound = found}
end
imgShow = cv.resize {imgShow, {imgShow:size(2) * self.imgShowRescale, imgShow:size(1) * self.imgShowRescale}}
cv.imshow {"camPoseDebug", imgShow}
cv.waitKey {1000}
cv.destroyWindow {winname = "camPoseDebug"}
end
return camPoseFinal, points
end
function PatternLocalisation:calcCamPose(inputImg, camIntrinsics, patternData, doDebug, imgShowInput, patternID)
doDebug = doDebug or false
imgShowInput = imgShowInput or nil
patternID = patternID or nil
local camPoseFinal
print("Searching calibration target.")
local found = false
local points
if inputImg:dim() == 3 then
if inputImg:size(3) > 1 then
-- extract green channel (e.g. of color cams with RGB Bayer Matrix)
local greenImgLeft = inputImg[{{},{},2}]:clone()
inputImg = greenImgLeft
end
end
local foundMarkers = self:processImg(inputImg, false) -- if too many circle points are found, point clusters are detected in each of which we search for the pattern
if next(foundMarkers) ~= nil then
if patternID ~= nil then
local m = findMarker(foundMarkers, patternID)
if m then
points = m.points
found = true
else
print(string.format("[Warning] Pattern with ID %d not found", patternID))
end
else
points = foundMarkers[1].points
found = true
end
else
print('[Warning] Trying fallback with standard findCirclesGrid() function...')
found, points = cv.findCirclesGrid { image = inputImg,
patternSize = { height = self.pattern.height, width = self.pattern.width },
flags = cv.CALIB_CB_ASYMMETRIC_GRID
}
if found and patternID ~= nil then
local id = self:getPatternId(inputImg, points, self.pattern)
if id ~= patternID then
print(string.format("[Warning] Pattern with ID %d not found", patternID))
found = false
end
else
if not found then
print("[Warning] No pattern found")
end
end
end
if found then
local points3d = self:generatePatternPoints(patternData.width, patternData.height, patternData.pointDist)
local poseFound, poseCamRotVector, poseCamTrans =
cv.solvePnP {
objectPoints = points3d,
imagePoints = points,
cameraMatrix = camIntrinsics,
distCoeffs = torch.DoubleTensor(1, 5):zero()
}
local poseCamRotMatrix = self:rotVectorToMat3x3(poseCamRotVector)
camPoseFinal = torch.DoubleTensor(4, 4):zero()
camPoseFinal[{{1, 3}, {1, 3}}] = poseCamRotMatrix
camPoseFinal[{{1, 3}, {4}}] = poseCamTrans
camPoseFinal[4][4] = 1
end
if doDebug then
local imgShow
if imgShowInput ~= nil then
imgShow = imgShowInput
else
imgShow = self:grayToRGB(inputImg)
end
if found then
cv.drawChessboardCorners {image = imgShow, patternSize = { height = patternData.height, width = patternData.width }, corners = points, patternWasFound = found}
end
imgShow = cv.resize {imgShow, {imgShow:size(2) * self.imgShowRescale, imgShow:size(1) * self.imgShowRescale}}
cv.imshow {"camPoseDebug", imgShow}
cv.waitKey {500}
end
return camPoseFinal, points
end
function PatternLocalisation:calcCamPoseViaPlaneFit(imgLeft, imgRight, whichCam, doDebug, imgShowInput, patternID)
local whichCam = whichCam or "left"
local doDebug = doDebug or false
local imgShowInput = imgShowInput or nil
local patternID = patternID or nil
local camPoseFinal
stereoCalib = self.stereoCalibration
local leftCamMat = stereoCalib.camLeftMatrix
local rightCamMat = stereoCalib.camRightMatrix
local leftDistCoeffs = stereoCalib.camLeftDistCoeffs
local rightDistCoeffs = stereoCalib.camRightDistCoeffs
local rightLeftCamTrafo = stereoCalib.trafoLeftToRightCam
-- Stereo Rectify:
local R = rightLeftCamTrafo[{{1, 3}, {1, 3}}]:double()
local T = rightLeftCamTrafo[{{1, 3}, {4}}]:double()
local leftR = torch.DoubleTensor(3, 3)
local rightR = torch.DoubleTensor(3, 3)
local leftP = torch.DoubleTensor(3, 4)
local rightP = torch.DoubleTensor(3, 4)
local Q = torch.DoubleTensor(4, 4)
cv.stereoRectify {
cameraMatrix1 = leftCamMat,
distCoeffs1 = leftDistCoeffs,
cameraMatrix2 = rightCamMat,
distCoeffs2 = rightDistCoeffs,
imageSize = {imgLeft:size(2), imgLeft:size(1)},
R = R,
T = T,
R1 = leftR,
R2 = rightR,
P1 = leftP,
P2 = rightP,
Q = Q,
flags = 0
}
-- Undistortion + rectification:
local mapAImgLeft, mapBImgLeft =
cv.initUndistortRectifyMap {
cameraMatrix = leftCamMat,
distCoeffs = leftDistCoeffs,
R = leftR,
newCameraMatrix = leftP,
size = {imgLeft:size(2), imgLeft:size(1)},
m1type = cv.CV_32FC1
}
local imgLeftRectUndist =
cv.remap {src = imgLeft, map1 = mapAImgLeft, map2 = mapBImgLeft, interpolation = cv.INTER_NEAREST}
local mapAImgRight, mapBImgRight =
cv.initUndistortRectifyMap {
cameraMatrix = rightCamMat,
distCoeffs = rightDistCoeffs,
R = rightR,
newCameraMatrix = rightP,
size = {imgRight:size(2), imgRight:size(1)},
m1type = cv.CV_32FC1
}
local imgRightRectUndist =
cv.remap {src = imgRight, map1 = mapAImgRight, map2 = mapBImgRight, interpolation = cv.INTER_NEAREST}
-- Detect all circle points of the pattern in the left/right image
-- (see "AutoCalibration.lua", function "extractPoints")
--------------------------------------------------------------------
print("Searching calibration target.")
local ok1, ok2 = false, false
local circlesGridPointsLeft
local circlesGridPointsRight
-- Searching calibration target in left camera image:
if imgLeftRectUndist:dim()> 2 and imgLeftRectUndist:size(3) > 1 then
-- extract green channel (e.g. of color cams with RGB Bayer Matrix)
local greenImgLeft = imgLeftRectUndist[{{},{},2}]:clone()
imgLeftRectUndist = greenImgLeft
end
local foundMarkersLeft = self:processImg(imgLeftRectUndist, false) -- if too many circle points are found, point clusters are detected in each of which is searched for the pattern
if next(foundMarkersLeft) ~= nil then
if patternID ~= nil then
local m = findMarker(foundMarkersLeft, patternID)
if m then
circlesGridPointsLeft = m.points
ok1 = true
else
print(string.format("[Warning] Pattern with ID %d not found in left image", patternID))
end
else
circlesGridPointsLeft = foundMarkersLeft[1].points
ok1 = true
end
else
print('[Warning] Trying fallback with standard findCirclesGrid() function...')
local ok, points = cv.findCirclesGrid { image = imgLeftRectUndist,
patternSize = { height = self.pattern.height, width = self.pattern.width },
flags = cv.CALIB_CB_ASYMMETRIC_GRID
}
if ok and patternID ~= nil then
local id = self:getPatternId(imgLeftRectUndist, points, self.pattern)
if id == patternID then
circlesGridPointsLeft = points
ok1 = true
else
print(string.format("[Warning] Pattern with ID %d not found in left image", patternID))
end
else
if ok then
circlesGridPointsLeft = points
ok1 = true
else
print("[Warning] No pattern found in left image")
end
end
end
-- Searching calibration target in right camera image:
if imgRightRectUndist:dim()> 2 and imgRightRectUndist:size(3) > 1 then
-- extract green channel (e.g. of color cams with RGB Bayer Matrix)
local greenImgRight = imgRightRectUndist[{{},{},2}]:clone()
imgRightRectUndist = greenImgRight
end
local foundMarkersRight = self:processImg(imgRightRectUndist, false) -- if too many circle points are found, point clusters are detected in each of which is searched for the pattern
if next(foundMarkersRight) ~= nil then
if patternID ~= nil then
local m = findMarker(foundMarkersRight, patternID)
if m then
circlesGridPointsRight = m.points
ok2 = true
else
print(string.format("[Warning] Pattern with ID %d not found in right image", patternID))
end
else
circlesGridPointsRight = foundMarkersRight[1].points
ok2 = true
end
else
print('[Warning] Trying fallback with standard findCirclesGrid() function...')
local ok, points = cv.findCirclesGrid { image = imgRightRectUndist,
patternSize = { height = self.pattern.height, width = self.pattern.width },
flags = cv.CALIB_CB_ASYMMETRIC_GRID
}
if ok and patternID ~= nil then
local id = self:getPatternId(imgRightRectUndist, points, self.pattern)
if id == patternID then
circlesGridPointsRight = points
ok2 = true
else
print(string.format("[Warning] Pattern with ID %d not foundin right image", patternID))
end
else
if ok then
circlesGridPointsRight = points
ok2 = true
else
print("[Warning] No pattern found in right image")
end
end
end
print(string.format("ok1: %s", ok1))
print(string.format("ok2: %s\n", ok2))
if doDebug then
local imgShowLeft = self:grayToRGB(imgLeftRectUndist)
if ok1 then
cv.drawChessboardCorners {image = imgShowLeft, patternSize = { height = self.pattern.height, width = self.pattern.width }, corners = circlesGridPointsLeft, patternWasFound = ok1}
end
imgShowLeft = cv.resize {imgShowLeft, {imgShowLeft:size(2) * self.imgShowRescale, imgShowLeft:size(1) * self.imgShowRescale}}
cv.imshow {"camPoseLeftDebug", imgShowLeft}
cv.waitKey {500}
local imgShowRight = self:grayToRGB(imgRightRectUndist)
if ok2 then
cv.drawChessboardCorners {image = imgShowRight, patternSize = { height = self.pattern.height, width = self.pattern.width }, corners = circlesGridPointsRight, patternWasFound = ok2}
end
imgShowRight = cv.resize {imgShowRight, {imgShowRight:size(2) * self.imgShowRescale, imgShowRight:size(1) * self.imgShowRescale}}
cv.imshow {"camPoseRightDebug", imgShowRight}
cv.waitKey {500}
end
local ok = ok1 and ok2
if ok then
-- Save 2d grid points.
local nPoints = self.pattern.width * self.pattern.height
local leftProjPoints = torch.DoubleTensor(2, nPoints) -- 2D coordinates (x,y) x #Points
local rightProjPoints = torch.DoubleTensor(2, nPoints)
for i = 1, nPoints do
leftProjPoints[1][i] = circlesGridPointsLeft[i][1][1]
leftProjPoints[2][i] = circlesGridPointsLeft[i][1][2]
rightProjPoints[1][i] = circlesGridPointsRight[i][1][1]
rightProjPoints[2][i] = circlesGridPointsRight[i][1][2]
end
local resulting4DPoints = torch.DoubleTensor(4, nPoints)
-- TriangulatePoints:
---------------------
cv.triangulatePoints {leftP, rightP, leftProjPoints, rightProjPoints, resulting4DPoints}
local resulting3DPoints = torch.DoubleTensor(nPoints, 3)
for i = 1, nPoints do
resulting3DPoints[i][1] = resulting4DPoints[1][i] / resulting4DPoints[4][i]
resulting3DPoints[i][2] = resulting4DPoints[2][i] / resulting4DPoints[4][i]
resulting3DPoints[i][3] = resulting4DPoints[3][i] / resulting4DPoints[4][i]
end
local pointsInCamCoords = torch.DoubleTensor(nPoints, 3)
if whichCam == "left" then
for i = 1, nPoints do
pointsInCamCoords[i] = torch.inverse(leftR) * resulting3DPoints[i]
end
else
for i = 1, nPoints do
pointsInCamCoords[i] = torch.inverse(rightR) * resulting3DPoints[i]
end
end
-- Generate plane through detected 3d points to get the transformation
----------------------------------------------------------------------
-- of the pattern into the coordinatesystem of the camera:
----------------------------------------------------------
-- Plane fit with pseudo inverse:
local A = torch.DoubleTensor(nPoints, 3) -- 2-dim. tensor of size 168 x 3
local b = torch.DoubleTensor(nPoints) -- 1-dim. tensor of size 168
for i = 1, nPoints do
A[i][1] = pointsInCamCoords[i][1]
A[i][2] = pointsInCamCoords[i][2]
A[i][3] = 1.0
b[i] = pointsInCamCoords[i][3]
end
-- Calculate x = A^-1 * b = (A^T A)^-1 * A^T * b (with pseudo inverse of A)
local At = A:transpose(1, 2)
local x = torch.mv(torch.mm(torch.inverse(torch.mm(At, A)), At), b)
-- Determine z-axis as normal on plane:
local n = torch.DoubleTensor(3)
n[1] = x[1]
n[2] = x[2]
n[3] = -1.0
local z_unit_vec = torch.div(n, torch.norm(n))
-- Determine x-axis along left boundary points of the pattern
local x_direction = pointsInCamCoords[self.pattern.width] - pointsInCamCoords[1]
local x_unit_vec = torch.div(x_direction, torch.norm(x_direction))
-- Determine y-axis along top boundary points of the pattern:
local y_direction = pointsInCamCoords[nPoints - self.pattern.width + 1] - pointsInCamCoords[1]
local y_unit_vec = torch.div(y_direction, torch.norm(y_direction))
-- Check, whether the normal vector z_unit_vec points into the correct direction.
local cross_product = torch.DoubleTensor(3)
cross_product = torch.cross(x_unit_vec, y_unit_vec)
cross_product = torch.div(cross_product, torch.norm(cross_product))
if z_unit_vec * cross_product < 0.0 then
z_unit_vec = -1.0 * z_unit_vec
end
-- x_unit_vec * z_unit_vec has to be zero.
-- Map x_unit_vec onto plane.
local new_x_unit_vec = x_unit_vec - x_unit_vec * z_unit_vec * z_unit_vec
if new_x_unit_vec * x_unit_vec < 0.0 then
new_x_unit_vec = -1.0 * new_x_unit_vec
end
-- Determine new y_unit_vec as cross product of x_unit_vec and z_unit_vec:
local new_y_unit_vec = torch.cross(new_x_unit_vec, z_unit_vec)
if new_y_unit_vec * y_unit_vec < 0.0 then
new_y_unit_vec = -1.0 * new_y_unit_vec
end
local newer_x_unit_vec = torch.cross(new_y_unit_vec, z_unit_vec)
newer_x_unit_vec = torch.div(newer_x_unit_vec, torch.norm(newer_x_unit_vec))
new_y_unit_vec = torch.div(new_y_unit_vec, torch.norm(new_y_unit_vec))
z_unit_vec = torch.div(z_unit_vec, torch.norm(z_unit_vec))
-- Transform pattern coordinate system into camera coordinate system:
-- M_B->A = (x_unit_vec, y_unit_vec, z_unit_vec, support vector)
camPoseFinal = torch.DoubleTensor(4, 4):zero()
camPoseFinal[{{1, 3}, {1}}] = newer_x_unit_vec
camPoseFinal[{{1, 3}, {2}}] = new_y_unit_vec
camPoseFinal[{{1, 3}, {3}}] = z_unit_vec
camPoseFinal[{{1, 3}, {4}}] = pointsInCamCoords[1] -- = support vector
camPoseFinal[4][4] = 1
else
print("PATTERN NOT FOUND!!!")
camPoseFinal = torch.eye(4)
end
return ok, camPoseFinal, circlesGridPointsLeft, circlesGridPointsRight
end
function PatternLocalisation:calcCamPoseMirrored(pointsResorted)
local points3d = self:generatePatternPoints(self.pattern.width, self.pattern.height, self.pattern.pointDist)
local poseFound, poseCamRotVector, poseCamTrans =
cv.solvePnP {
objectPoints = points3d,
imagePoints = pointsResorted,
cameraMatrix = self.camIntrinsics,
distCoeffs = torch.DoubleTensor(1, 5):zero()
}
print(poseFound)
print(poseCamRotVector)
print("done")
local poseCamRotMatrix = self:rotVectorToMat3x3(poseCamRotVector)
local camPoseFinal = torch.DoubleTensor(4, 4):zero()
camPoseFinal[{{1, 3}, {1, 3}}] = poseCamRotMatrix
camPoseFinal[{{1, 3}, {4}}] = poseCamTrans
camPoseFinal[4][4] = 1
return camPoseFinal
end
-- Calculates a rectangle of a point set (torch.Tensor of dim n,2) , usefull for ROI or cropping
function PatternLocalisation:calcBoundingRect(pointTensor, border, imgWidth, imgHeight)
local points = torch.squeeze(pointTensor)
local rectPoints = cv.boundingRect {points}
local rect = torch.IntTensor(2, 2):zero() -- top left and bottom right corner of the ROI rect
if rectPoints.x - border >= 1 then
rect[1][1] = rectPoints.x - border
else
rect[1][1] = 1
end
if rectPoints.y - border >= 1 then
rect[1][2] = rectPoints.y - border
else
rect[1][2] = 1
end
if rectPoints.x + rectPoints.width + border < imgWidth then
rect[2][1] = rectPoints.x + rectPoints.width + border
else
rect[2][1] = imgWidth
end
if rectPoints.y + rectPoints.height + border < imgHeight then
rect[2][2] = rectPoints.y + rectPoints.height + border
else
rect[2][2] = imgHeight
end
return rect
end
-- Calculates the cam pose for a pattern. The pattern has to be the only pattern within the region of interesst defined by rectROI
function PatternLocalisation:calcCamPoseROI(inputImg, rectROI, doDebug)
doDebug = doDebug or false
if inputImg:dim() ~= 2 then
print("Only 2dim grayscale images supported (for speed reason). Provided image has size ")
print(inputImg:size())
return nil
end
local imgROI = torch.ByteTensor(inputImg:size(1), inputImg:size(2)):fill(255)
imgROI[{{rectROI[1][2], rectROI[2][2]}, {rectROI[1][1], rectROI[2][1]}}] =
inputImg[{{rectROI[1][2], rectROI[2][2]}, {rectROI[1][1], rectROI[2][1]}}]
if doDebug == true then
local imgShow
if self.imgShowRescale ~= nil then
imgShow = cv.resize {imgROI, {imgROI:size(2) * self.imgShowRescale, imgROI:size(1) * self.imgShowRescale}}
else
imgShow = imgROI
end
cv.imshow {"imgPatROI", imgShow}
cv.waitKey {1000}
cv.destroyWindow {winname = "imgPatROI"}
end
return self:processImg(imgROI)
end
function PatternLocalisation:findCircles(inputImg, doDebug)
-- Setup SimpleBlobDetector parameters.
local blobDetector = cv.SimpleBlobDetector {self.circleFinderParams}
local resultsTmp = blobDetector:detect {image = inputImg}
local results = {}
for i = 1, resultsTmp.size do
table.insert(
results,
{
radius = resultsTmp.data[i].size / 2.0,
angle = resultsTmp.data[i].angle,
pos = torch.DoubleTensor({resultsTmp.data[i].pt.x, resultsTmp.data[i].pt.y, 1})
}
)
end
local circleScale = 16
local shiftBits = 4
if doDebug == true then
local rescaleFactor = 1
if self.imgShowRescale ~= nil then
rescaleFactor = self.imgShowRescale
end
local imgScale = cv.resize {inputImg, {inputImg:size(2) * rescaleFactor, inputImg:size(1) * rescaleFactor}}
imgScale = self:grayToRGB(imgScale)
for key, val in ipairs(results) do
cv.circle {
img = imgScale,
center = {x = val.pos[1] * rescaleFactor * circleScale, y = val.pos[2] * rescaleFactor * circleScale},
radius = val.radius * rescaleFactor * circleScale,
color = {0, 255, 255},
thickness = 2,
lineType = cv.LINE_AA,
shift = shiftBits
}
end
cv.imshow {"circleFinder", imgScale}
cv.waitKey {500}
end
return results
end
-- cluster: list, containing index numbers of list circleCenters
function PatternLocalisation:expandCluster(
kdtree,
circleCenters,
eps,
minNPoints,
currPointIndex,
neighbours,
pointStatus,
cluster)
table.insert(cluster, currPointIndex)
pointStatus[currPointIndex] = bit.bor(pointStatus[currPointIndex], self.clusterStatus.kAssigned)
-- convert torchTensor to list so we can append points
local neighbourList = {}
for i = 1, neighbours:size(2) do
table.insert(neighbourList, neighbours[1][i])
end
local loopEnd = #neighbourList
local i = 1
while i <= loopEnd do
local index = neighbourList[i]
if bit.band(pointStatus[index], self.clusterStatus.kProcessed) == 0 then
pointStatus[index] = bit.bor(pointStatus[index], self.clusterStatus.kProcessed)
local queryPoint = torch.FloatTensor(1, 2)
queryPoint[1][1] = circleCenters[index].pos[1]
queryPoint[1][2] = circleCenters[index].pos[2]
local indices = torch.IntTensor(1, minNPoints):fill(0)
local dists = torch.FloatTensor(1, minNPoints):fill(0)
local tmp -- not used
tmp, indices, dists =
kdtree:radiusSearch {
query = queryPoint,
radius = eps * eps,
maxResults = minNPoints,
indices = indices,
dists = dists
}
if indices[1][minNPoints] > 0 then
for i = 1, indices:size(2) do
table.insert(neighbourList, indices[1][i])
loopEnd = #neighbourList
end
end
end
if bit.band(pointStatus[index], self.clusterStatus.kAssigned) == 0 then
table.insert(cluster, index)
pointStatus[index] = bit.bor(pointStatus[index], self.clusterStatus.kAssigned)
end
i = i + 1
end
end
function PatternLocalisation:DBScan(circleCenters, eps, minNPoints)
local clusterList = {}
if #circleCenters < 1 then
return clusterList -- return an empty cluster list because clustering less then one point is not possible
end
local circleCentersTensor = torch.FloatTensor(#circleCenters, 2)
for i, val in ipairs(circleCenters) do
circleCentersTensor[i][1] = val.pos[1]
circleCentersTensor[i][2] = val.pos[2]
end
local params = cv.flann.KDTreeIndexParams {trees = 10}
local kdtree = cv.flann.Index {circleCentersTensor, params, cv.FLANN_DIST_EUCLIDEAN}
local pointStatus = torch.ByteTensor(#circleCenters):fill(self.clusterStatus.kUnprocessed)
for i = 1, #circleCenters do
if bit.band(pointStatus[i], self.clusterStatus.kProcessed) == 0 then
pointStatus[i] = bit.bor(pointStatus[i], self.clusterStatus.kProcessed)
local queryPoint = torch.FloatTensor(1, 2)
queryPoint[1][1] = circleCenters[i].pos[1]
queryPoint[1][2] = circleCenters[i].pos[2]
-- indices and dists are 1xn int and float tensors, respectivly
local indices = torch.IntTensor(1, minNPoints):fill(0)
local dists = torch.FloatTensor(1, minNPoints):fill(0)
local tmp -- not used
tmp, indices, dists =
kdtree:radiusSearch {
query = queryPoint,
radius = eps * eps,
maxResults = minNPoints,
indices = indices,
dists = dists
}
if indices[1][minNPoints] <= 0 or indices[1][minNPoints] ~= indices[1][minNPoints] then -- 0 or nan
pointStatus[i] = bit.bor(pointStatus[i], self.clusterStatus.kNoise)
else
local nextCluster = {}
table.insert(clusterList, nextCluster)
self:expandCluster(kdtree, circleCenters, eps, minNPoints, i, indices, pointStatus, nextCluster)
end
end
end
return clusterList
end
-- Debugging function
function PatternLocalisation:espChecking(circleCentersInput, queryX, queryY, debugImg)
local circleCenters = torch.FloatTensor(#circleCentersInput, 2)
for i, val in ipairs(circleCentersInput) do
circleCenters[i][1] = val.pos[1]
circleCenters[i][2] = val.pos[2]
end
local params = cv.flann.KDTreeIndexParams {trees = 10}
local kdtree = cv.flann.Index {circleCenters, params, cv.FLANN_DIST_EUCLIDEAN}
local queryPoint = torch.FloatTensor(1, 2)
queryPoint[1][1] = queryX
queryPoint[1][2] = queryY
local nNeighbours = 6
local indices, dists = kdtree:knnSearch {queryPoint, nNeighbours}
local circleScale = 16
local shiftBits = 4
local rescaleFactor = 1.0
cv.circle {
img = debugImg,
center = {x = queryPoint[1][1] * rescaleFactor * circleScale, y = queryPoint[1][2] * rescaleFactor * circleScale},
radius = 5 * circleScale,
color = {50, 50, 255},
thickness = 3,
lineType = cv.LINE_AA,
shift = shiftBits
}
for i = 1, nNeighbours do
local center = {}
center.x = circleCentersInput[indices[1][i]].pos[1] * rescaleFactor * circleScale
center.y = circleCentersInput[indices[1][i]].pos[2] * rescaleFactor * circleScale
local radius = circleCentersInput[indices[1][i]].radius * rescaleFactor * circleScale
cv.circle {
img = debugImg,
center = center,
radius = radius,
color = {255, 0, 255},
thickness = 1,
lineType = cv.LINE_AA,
shift = shiftBits
}
end
cv.imshow {"testESP", debugImg}
cv.waitKey {1000}
end
-- Set all pixels to color color, except inside the polygon defined by points
-- points is torch.IntTensor(nPolygonPoints, 2)
function PatternLocalisation:maskImage(inputImg, points, color)
color = color or 255
local mask = torch.ByteTensor(inputImg:size(1), inputImg:size(2), 1):fill(1)
cv.fillConvexPoly {mask, points, {0}}
local applyMask = torch.eq(mask, 1)
-- If image is RGB image, expand the mask to contain all three channels
if inputImg:dim() == 3 and inputImg:size(3) == 3 then
applyMask = applyMask:expand((#applyMask)[1], (#applyMask)[2], 3)
end
-- apply the mask to a copy of the provided image
local imgMasked = inputImg:clone()