-
Notifications
You must be signed in to change notification settings - Fork 138
/
KinectProjector.cpp
2147 lines (1875 loc) · 72.6 KB
/
KinectProjector.cpp
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
/***********************************************************************
KinectProjector - KinectProjector takes care of the spatial conversion
between the various coordinate systems, control the kinectgrabber and
perform the calibration of the kinect and projector.
Copyright (c) 2016-2017 Thomas Wolf and Rasmus R. Paulsen (people.compute.dtu.dk/rapa)
This file is part of the Magic Sand.
The Magic Sand 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 (at your option) any later version.
The Magic Sand 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 the Magic Sand; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
#include "KinectProjector.h"
#include <sstream>
using namespace ofxCSG;
KinectProjector::KinectProjector(std::shared_ptr<ofAppBaseWindow> const& p)
:ROIcalibrated(false),
projKinectCalibrated(false),
//calibrating (false),
basePlaneUpdated (false),
basePlaneComputed(false),
projKinectCalibrationUpdated (false),
//ROIUpdated (false),
imageStabilized (false),
waitingForFlattenSand (false),
drawKinectView(false),
drawKinectColorView(true)
{
doShowROIonProjector = false;
applicationState = APPLICATION_STATE_SETUP;
projWindow = p;
TemporalFilteringType = 1;
DumpDebugFiles = true;
DebugFileOutDir = "DebugFiles//";
}
void KinectProjector::setup(bool sdisplayGui)
{
applicationState = APPLICATION_STATE_SETUP;
ofAddListener(ofEvents().exit, this, &KinectProjector::exit);
// instantiate the modal windows //
modalTheme = make_shared<ofxModalThemeProjKinect>();
confirmModal = make_shared<ofxModalConfirm>();
confirmModal->setTheme(modalTheme);
confirmModal->addListener(this, &KinectProjector::onConfirmModalEvent);
confirmModal->setButtonLabel("Ok");
calibModal = make_shared<ofxModalAlert>();
calibModal->setTheme(modalTheme);
calibModal->addListener(this, &KinectProjector::onCalibModalEvent);
calibModal->setButtonLabel("Cancel");
displayGui = sdisplayGui;
// calibration chessboard config
chessboardSize = 300;
chessboardX = 5;
chessboardY = 4;
// Gradient Field
gradFieldResolution = 10;
arrowLength = 25;
// Setup default base plane
basePlaneNormalBack = ofVec3f(0,0,1); // This is our default baseplane normal
basePlaneOffsetBack= ofVec3f(0,0,870); // This is our default baseplane offset
basePlaneNormal = basePlaneNormalBack;
basePlaneOffset = basePlaneOffsetBack;
basePlaneEq=getPlaneEquation(basePlaneOffset,basePlaneNormal);
maxOffsetBack = basePlaneOffset.z-300;
maxOffset = maxOffsetBack;
maxOffsetSafeRange = 50; // Range above the autocalib measured max offset
// kinectgrabber: start & default setup
kinectOpened = kinectgrabber.setup();
lastKinectOpenTry = ofGetElapsedTimef();
if (!kinectOpened)
{
// If the kinect is not found and opened (which happens very often on Windows 10) then just go with default values for the Kinect
ofLogVerbose("KinectProjector") << "KinectProjector.setup(): Kinect not found - trying again later";
}
doInpainting = false;
doFullFrameFiltering = false;
spatialFiltering = true;
followBigChanges = false;
numAveragingSlots = 15;
TemporalFrameCounter = 0;
// Get projector and kinect width & height
projRes = ofVec2f(projWindow->getWidth(), projWindow->getHeight());
kinectRes = kinectgrabber.getKinectSize();
kinectROI = ofRectangle(0, 0, kinectRes.x, kinectRes.y);
ofLogVerbose("KinectProjector") << "KinectProjector.setup(): kinectROI " << kinectROI;
// Initialize the fbos and images
FilteredDepthImage.allocate(kinectRes.x, kinectRes.y);
kinectColorImage.allocate(kinectRes.x, kinectRes.y);
thresholdedImage.allocate(kinectRes.x, kinectRes.y);
kpt = new ofxKinectProjectorToolkit(projRes, kinectRes);
// finish kinectgrabber setup and start the grabber
kinectgrabber.setupFramefilter(gradFieldResolution, maxOffset, kinectROI, spatialFiltering, followBigChanges, numAveragingSlots);
kinectWorldMatrix = kinectgrabber.getWorldMatrix();
ofLogVerbose("KinectProjector") << "KinectProjector.setup(): kinectWorldMatrix: " << kinectWorldMatrix ;
// Setup gradient field
setupGradientField();
fboProjWindow.allocate(projRes.x, projRes.y, GL_RGBA);
fboProjWindow.begin();
ofClear(255, 255, 255, 0);
ofBackground(255); // Set to white in setup mode
fboProjWindow.end();
fboMainWindow.allocate(kinectRes.x, kinectRes.y, GL_RGBA);
fboMainWindow.begin();
ofClear(255, 255, 255, 0);
fboMainWindow.end();
if (displayGui)
setupGui();
kinectgrabber.start(); // Start the acquisition
updateStatusGUI();
}
void KinectProjector::exit(ofEventArgs& e)
{
if (ROIcalibrated)
{
if (saveSettings())
{
ofLogVerbose("KinectProjector") << "exit(): Settings saved ";
}
else {
ofLogVerbose("KinectProjector") << "exit(): Settings could not be saved ";
}
}
}
void KinectProjector::setupGradientField(){
gradFieldcols = kinectRes.x / gradFieldResolution;
gradFieldrows = kinectRes.y / gradFieldResolution;
gradField = new ofVec2f[gradFieldcols*gradFieldrows];
ofVec2f* gfPtr=gradField;
for(unsigned int y=0;y<gradFieldrows;++y)
for(unsigned int x=0;x<gradFieldcols;++x,++gfPtr)
*gfPtr=ofVec2f(0);
}
void KinectProjector::setGradFieldResolution(int sgradFieldResolution){
gradFieldResolution = sgradFieldResolution;
setupGradientField();
kinectgrabber.performInThread([sgradFieldResolution](KinectGrabber & kg) {
kg.setGradFieldResolution(sgradFieldResolution);
});
}
// For some reason this call eats milliseconds - so it should only be called when something is changed
// else it would be convenient just to call it in every update
void KinectProjector::updateStatusGUI()
{
if (kinectOpened)
{
StatusGUI->getLabel("Kinect Status")->setLabel("Kinect running");
StatusGUI->getLabel("Kinect Status")->setLabelColor(ofColor(0, 255, 0));
}
else
{
StatusGUI->getLabel("Kinect Status")->setLabel("Kinect not found");
StatusGUI->getLabel("Kinect Status")->setLabelColor(ofColor(255, 0, 0));
}
if (ROIcalibrated)
{
StatusGUI->getLabel("ROI Status")->setLabel("ROI defined");
StatusGUI->getLabel("ROI Status")->setLabelColor(ofColor(0, 255, 0));
}
else
{
StatusGUI->getLabel("ROI Status")->setLabel("ROI not defined");
StatusGUI->getLabel("ROI Status")->setLabelColor(ofColor(255, 0, 0));
}
if (basePlaneComputed)
{
StatusGUI->getLabel("Baseplane Status")->setLabel("Baseplane found");
StatusGUI->getLabel("Baseplane Status")->setLabelColor(ofColor(0, 255, 0));
}
else
{
StatusGUI->getLabel("Baseplane Status")->setLabel("Baseplane not found");
StatusGUI->getLabel("Baseplane Status")->setLabelColor(ofColor(255, 0, 0));
}
if (projKinectCalibrated)
{
StatusGUI->getLabel("Calibration Status")->setLabel("Projector/Kinect calibrated");
StatusGUI->getLabel("Calibration Status")->setLabelColor(ofColor(0, 255, 0));
}
else
{
StatusGUI->getLabel("Calibration Status")->setLabel("Projector/Kinect not calibrated");
StatusGUI->getLabel("Calibration Status")->setLabelColor(ofColor(255, 0, 0));
}
StatusGUI->getLabel("Projector Status")->setLabel("Projector " + ofToString(projRes.x) + " x " + ofToString(projRes.y));
std::string AppStatus = "Setup";
if (applicationState == APPLICATION_STATE_CALIBRATING)
AppStatus = "Calibrating";
else if (applicationState == APPLICATION_STATE_RUNNING)
AppStatus = "Running";
StatusGUI->getLabel("Application Status")->setLabel("Application state: " + AppStatus);
StatusGUI->getLabel("Application Status")->setLabelColor(ofColor(255, 255, 0));
StatusGUI->getLabel("Calibration Step")->setLabel("Calibration Step: " + calibrationText);;
StatusGUI->getLabel("Calibration Step")->setLabelColor(ofColor(0, 255, 255));
gui->getToggle("Spatial filtering")->setChecked(spatialFiltering);
gui->getToggle("Quick reaction")->setChecked(followBigChanges);
gui->getToggle("Inpaint outliers")->setChecked(doInpainting);
gui->getToggle("Full Frame Filtering")->setChecked(doFullFrameFiltering);
}
void KinectProjector::update()
{
// Clear updated state variables
basePlaneUpdated = false;
// ROIUpdated = false;
projKinectCalibrationUpdated = false;
// Try to open the kinect every 3. second if it is not yet open
float TimeStamp = ofGetElapsedTimef();
if (!kinectOpened && TimeStamp-lastKinectOpenTry > 3)
{
lastKinectOpenTry = TimeStamp;
kinectOpened = kinectgrabber.openKinect();
if (kinectOpened)
{
ofLogVerbose("KinectProjector") << "KinectProjector.update(): A Kinect was found ";
kinectRes = kinectgrabber.getKinectSize();
kinectROI = ofRectangle(0, 0, kinectRes.x, kinectRes.y);
ofLogVerbose("KinectProjector") << "KinectProjector.update(): kinectROI " << kinectROI;
kinectgrabber.setupFramefilter(gradFieldResolution, maxOffset, kinectROI, spatialFiltering, followBigChanges, numAveragingSlots);
kinectWorldMatrix = kinectgrabber.getWorldMatrix();
ofLogVerbose("KinectProjector") << "KinectProjector.update(): kinectWorldMatrix: " << kinectWorldMatrix;
updateStatusGUI();
}
}
if (displayGui)
{
gui->update();
StatusGUI->update();
}
// Get images from kinect grabber
ofFloatPixels filteredframe;
if (kinectOpened && kinectgrabber.filtered.tryReceive(filteredframe))
{
fpsKinect.newFrame();
fpsKinectText->setText(ofToString(fpsKinect.getFps(), 2));
FilteredDepthImage.setFromPixels(filteredframe.getData(), kinectRes.x, kinectRes.y);
FilteredDepthImage.updateTexture();
// Get color image from kinect grabber
ofPixels coloredframe;
if (kinectgrabber.colored.tryReceive(coloredframe))
{
kinectColorImage.setFromPixels(coloredframe);
if (TemporalFilteringType == 0)
TemporalFrameFilter.NewFrame(kinectColorImage.getPixels().getData(), kinectColorImage.width, kinectColorImage.height);
else if (TemporalFilteringType == 1)
TemporalFrameFilter.NewColFrame(kinectColorImage.getPixels().getData(), kinectColorImage.width, kinectColorImage.height);
}
// Get gradient field from kinect grabber
kinectgrabber.gradient.tryReceive(gradField);
// Update grabber stored frame number
kinectgrabber.lock();
kinectgrabber.decStoredframes();
kinectgrabber.unlock();
// Is the depth image stabilized
imageStabilized = kinectgrabber.isImageStabilized();
// Are we calibrating ?
if (applicationState == APPLICATION_STATE_CALIBRATING && !waitingForFlattenSand)
{
updateCalibration();
}
else
{
//ofEnableAlphaBlending();
fboMainWindow.begin();
if (drawKinectView || drawKinectColorView)
{
if (drawKinectColorView)
{
kinectColorImage.updateTexture();
kinectColorImage.draw(0, 0);
}
else
{
FilteredDepthImage.draw(0, 0);
}
ofNoFill();
if (ROIcalibrated)
{
ofSetColor(0, 0, 255);
ofDrawRectangle(kinectROI);
}
ofSetColor(255, 0, 0);
ofDrawRectangle(1, 1, kinectRes.x-1, kinectRes.y-1);
if (calibrationState == CALIBRATION_STATE_ROI_MANUAL_DETERMINATION && ROICalibState == ROI_CALIBRATION_STATE_INIT)
{
int xmin = std::min((int)ROIStartPoint.x, (int)ROICurrentPoint.x);
int xmax = std::max((int)ROIStartPoint.x, (int)ROICurrentPoint.x);
int ymin = std::min((int)ROIStartPoint.y, (int)ROICurrentPoint.y);
int ymax = std::max((int)ROIStartPoint.y, (int)ROICurrentPoint.y);
if (xmin >= 0) // Start point has been set
{
ofSetColor(0, 255, 0);
ofRectangle tempRect(xmin, ymin, xmax - xmin, ymax - ymin);
ofDrawRectangle(tempRect);
}
}
}
else
{
ofClear(0, 0, 0, 0);
}
fboMainWindow.end();
}
}
fboProjWindow.begin();
if (applicationState != APPLICATION_STATE_CALIBRATING)
{
ofClear(255, 255, 255, 0);
}
if (doShowROIonProjector && ROIcalibrated && kinectOpened)
{
ofNoFill();
ofSetLineWidth(4);
// Draw rectangle of ROI using the offset by the current sand level
ofVec2f UL = kinectCoordToProjCoord(kinectROI.getMinX(), kinectROI.getMinY());
ofVec2f LR = kinectCoordToProjCoord(kinectROI.getMaxX()-1, kinectROI.getMaxY()-1);
ofSetColor(255, 0, 0);
ofRectangle tempRect(ofPoint(UL.x, UL.y), ofPoint(LR.x, LR.y));
ofDrawRectangle(tempRect);
ofSetColor(0, 0, 255);
ofRectangle tempRect2(ofPoint(UL.x - 2, UL.y - 2), ofPoint(UL.x + 2, UL.y + 2));
ofDrawRectangle(tempRect2);
// Draw rectangle of ROI using the offset by the waterlevel
UL = kinectCoordToProjCoord(kinectROI.getMinX(), kinectROI.getMinY(), basePlaneOffset.z);
LR = kinectCoordToProjCoord(kinectROI.getMaxX(), kinectROI.getMaxY(), basePlaneOffset.z);
ofSetColor(0, 255, 0);
tempRect = ofRectangle(ofPoint(UL.x, UL.y), ofPoint(LR.x, LR.y));
ofDrawRectangle(tempRect);
ofSetColor(255, 0, 255);
tempRect2 = ofRectangle(ofPoint(UL.x - 2, UL.y - 2), ofPoint(UL.x + 2, UL.y + 2));
ofDrawRectangle(tempRect2);
}
else if (applicationState == APPLICATION_STATE_SETUP)
{
ofBackground(255); // Set to white in setup mode
}
fboProjWindow.end();
}
void KinectProjector::mousePressed(int x, int y, int button)
{
if (calibrationState == CALIBRATION_STATE_ROI_MANUAL_DETERMINATION && ROICalibState == ROI_CALIBRATION_STATE_INIT)
{
ROIStartPoint.x = x;
ROIStartPoint.y = y;
ROICurrentPoint.x = x;
ROICurrentPoint.y = y;
}
else if (kinectOpened && drawKinectView)
{
int ind = y * kinectRes.x + x;
if (ind >= 0 && ind < FilteredDepthImage.getFloatPixelsRef().getTotalBytes())
{
float z = FilteredDepthImage.getFloatPixelsRef().getData()[ind];
std::cout << "Kinect depth (x, y, z) = (" << x << ", " << y << ", " << z << ")" << std::endl;
}
}
}
void KinectProjector::mouseReleased(int x, int y, int button)
{
if (calibrationState == CALIBRATION_STATE_ROI_MANUAL_DETERMINATION && ROICalibState == ROI_CALIBRATION_STATE_INIT)
{
if (ROIStartPoint.x >= 0)
{
x = std::max(0, x);
x = std::min((int)kinectRes.x - 1, x);
y = std::max(0, y);
y = std::min((int)kinectRes.y - 1, y);
ROICurrentPoint.x = x;
ROICurrentPoint.y = y;
int xmin = std::min((int)ROIStartPoint.x, (int)ROICurrentPoint.x);
int xmax = std::max((int)ROIStartPoint.x, (int)ROICurrentPoint.x);
int ymin = std::min((int)ROIStartPoint.y, (int)ROICurrentPoint.y);
int ymax = std::max((int)ROIStartPoint.y, (int)ROICurrentPoint.y);
ofRectangle tempRect(xmin, ymin, xmax - xmin, ymax - ymin);
kinectROI = tempRect;
setNewKinectROI();
ROICalibState = ROI_CALIBRATION_STATE_DONE;
calibrationText = "Manual ROI defined";
updateStatusGUI();
}
}
}
void KinectProjector::mouseDragged(int x, int y, int button)
{
if (calibrationState == CALIBRATION_STATE_ROI_MANUAL_DETERMINATION && ROICalibState == ROI_CALIBRATION_STATE_INIT)
{
x = std::max(0, x);
x = std::min((int)kinectRes.x-1, x);
y = std::max(0, y);
y = std::min((int)kinectRes.y - 1, y);
ROICurrentPoint.x = x;
ROICurrentPoint.y = y;
}
}
bool KinectProjector::getProjectionFlipped()
{
return (kinectProjMatrix(0, 0) < 0);
}
void KinectProjector::updateCalibration()
{
if (calibrationState == CALIBRATION_STATE_FULL_AUTO_CALIBRATION)
{
updateFullAutoCalibration();
} else if (calibrationState == CALIBRATION_STATE_ROI_AUTO_DETERMINATION){
updateROIAutoCalibration();
}
//else if (calibrationState == CALIBRATION_STATE_ROI_MANUAL_DETERMINATION)
//{
// updateROIManualCalibration();
// }
else if (calibrationState == CALIBRATION_STATE_PROJ_KINECT_AUTO_CALIBRATION){
updateProjKinectAutoCalibration();
}else if (calibrationState == CALIBRATION_STATE_PROJ_KINECT_MANUAL_CALIBRATION) {
updateProjKinectManualCalibration();
}
}
void KinectProjector::updateFullAutoCalibration()
{
if (fullCalibState == FULL_CALIBRATION_STATE_ROI_DETERMINATION)
{
// updateROIAutoCalibration();
updateROIFromFile();
if (ROICalibState == ROI_CALIBRATION_STATE_DONE)
{
fullCalibState = FULL_CALIBRATION_STATE_AUTOCALIB;
autoCalibState = AUTOCALIB_STATE_INIT_FIRST_PLANE;
}
}
else if (fullCalibState == FULL_CALIBRATION_STATE_AUTOCALIB)
{
updateProjKinectAutoCalibration();
if (autoCalibState == AUTOCALIB_STATE_DONE)
{
fullCalibState = FULL_CALIBRATION_STATE_DONE;
}
}
}
void KinectProjector::updateROIAutoCalibration()
{
//updateROIFromColorImage();
updateROIFromDepthImage();
}
void KinectProjector::updateROIFromCalibration()
{
ofVec2f a = worldCoordTokinectCoord(projCoordAndWorldZToWorldCoord(0, 0, basePlaneOffset.z));
ofVec2f b = worldCoordTokinectCoord(projCoordAndWorldZToWorldCoord(projRes.x, 0, basePlaneOffset.z));
ofVec2f c = worldCoordTokinectCoord(projCoordAndWorldZToWorldCoord(projRes.x, projRes.y, basePlaneOffset.z));
ofVec2f d = worldCoordTokinectCoord(projCoordAndWorldZToWorldCoord(0, projRes.y, basePlaneOffset.z));
float x1 = max(a.x, d.x);
float x2 = min(b.x, c.x);
float y1 = max(a.y, b.y);
float y2 = min(c.y, d.y);
ofRectangle smallKinectROI = ofRectangle(ofPoint(max(x1, kinectROI.getLeft()), max(y1, kinectROI.getTop())), ofPoint(min(x2, kinectROI.getRight()), min(y2, kinectROI.getBottom())));
kinectROI = smallKinectROI;
kinectROI.standardize();
ofLogVerbose("KinectProjector") << "updateROIFromCalibration(): final kinectROI : " << kinectROI;
setNewKinectROI();
}
//TODO: update color image ROI acquisition to use calibration modal
void KinectProjector::updateROIFromColorImage()
{
fboProjWindow.begin();
ofBackground(255);
fboProjWindow.end();
if (ROICalibState == ROI_CALIBRATION_STATE_INIT) { // set kinect to max depth range
ROICalibState = ROI_CALIBRATION_STATE_MOVE_UP;
large = ofPolyline();
threshold = 90;
} else if (ROICalibState == ROI_CALIBRATION_STATE_MOVE_UP) {
while (threshold < 255){
kinectColorImage.setROI(0, 0, kinectRes.x, kinectRes.y);
thresholdedImage = kinectColorImage;
cvThreshold(thresholdedImage.getCvImage(), thresholdedImage.getCvImage(), threshold, 255, CV_THRESH_BINARY_INV);
contourFinder.findContours(thresholdedImage, 12, kinectRes.x*kinectRes.y, 5, true);
ofPolyline small = ofPolyline();
for (int i = 0; i < contourFinder.nBlobs; i++) {
ofxCvBlob blobContour = contourFinder.blobs[i];
if (blobContour.hole) {
ofPolyline poly = ofPolyline(blobContour.pts);
if (poly.inside(kinectRes.x/2, kinectRes.y/2))
{
if (small.size() == 0 || poly.getArea() < small.getArea()) {
small = poly;
}
}
}
}
ofLogVerbose("KinectProjector") << "KinectProjector.updateROIFromColorImage(): small.getArea(): " << small.getArea() ;
ofLogVerbose("KinectProjector") << "KinectProjector.updateROIFromColorImage(): large.getArea(): " << large.getArea() ;
if (large.getArea() < small.getArea())
{
ofLogVerbose("KinectProjector") << "updateROIFromColorImage(): We take the largest contour line surroundings the center of the screen at all threshold level" ;
large = small;
}
threshold+=1;
}
kinectROI = large.getBoundingBox();
kinectROI.standardize();
ofLogVerbose("KinectProjector") << "updateROIFromColorImage(): kinectROI : " << kinectROI ;
ROICalibState = ROI_CALIBRATION_STATE_DONE;
setNewKinectROI();
} else if (ROICalibState == ROI_CALIBRATION_STATE_DONE){
}
}
void KinectProjector::updateROIFromDepthImage(){
int counter = 0;
if (ROICalibState == ROI_CALIBRATION_STATE_INIT) {
calibModal->setMessage("Enlarging acquisition area & resetting buffers.");
setMaxKinectGrabberROI();
calibModal->setMessage("Stabilizing acquisition.");
ROICalibState = ROI_CALIBRATION_STATE_READY_TO_MOVE_UP;
} else if (ROICalibState == ROI_CALIBRATION_STATE_READY_TO_MOVE_UP && imageStabilized) {
calibModal->setMessage("Scanning depth field to find sandbox walls.");
ofLogVerbose("KinectProjector") << "updateROIFromDepthImage(): ROI_CALIBRATION_STATE_READY_TO_MOVE_UP: got a stable depth image" ;
ROICalibState = ROI_CALIBRATION_STATE_MOVE_UP;
large = ofPolyline();
ofxCvFloatImage temp;
temp.setFromPixels(FilteredDepthImage.getFloatPixelsRef().getData(), kinectRes.x, kinectRes.y);
temp.setNativeScale(FilteredDepthImage.getNativeScaleMin(), FilteredDepthImage.getNativeScaleMax());
temp.convertToRange(0, 1);
thresholdedImage.setFromPixels(temp.getFloatPixelsRef());
threshold = 0; // We go from the higher distance to the kinect (lower position) to the lower distance
} else if (ROICalibState == ROI_CALIBRATION_STATE_MOVE_UP) {
ofLogVerbose("KinectProjector") << "updateROIFromDepthImage(): ROI_CALIBRATION_STATE_MOVE_UP";
while (threshold < 255){
cvThreshold(thresholdedImage.getCvImage(), thresholdedImage.getCvImage(), 255-threshold, 255, CV_THRESH_TOZERO_INV);
thresholdedImage.updateTexture();
// SaveDepthDebugImageNative(thresholdedImage, counter++);
contourFinder.findContours(thresholdedImage, 12, kinectRes.x*kinectRes.y, 5, true, false);
ofPolyline small = ofPolyline();
for (int i = 0; i < contourFinder.nBlobs; i++) {
ofxCvBlob blobContour = contourFinder.blobs[i];
if (blobContour.hole) {
ofPolyline poly = ofPolyline(blobContour.pts);
if (poly.inside(kinectRes.x/2, kinectRes.y/2))
{
if (small.size() == 0 || poly.getArea() < small.getArea()) {
small = poly;
}
}
}
}
if (large.getArea() < small.getArea())
{
ofLogVerbose("KinectProjector") << "updateROIFromDepthImage(): updating ROI" ;
large = small;
}
threshold+=1;
}
if (large.getArea() == 0)
{
ofLogVerbose("KinectProjector") << "Calibration failed: The sandbox walls could not be found";
calibModal->hide();
confirmModal->setTitle("Calibration failed");
confirmModal->setMessage("The sandbox walls could not be found.");
confirmModal->show();
// calibrating = false;
applicationState = APPLICATION_STATE_SETUP;
updateStatusGUI();
} else {
kinectROI = large.getBoundingBox();
// insideROIPoly = large.getResampledBySpacing(10);
kinectROI.standardize();
calibModal->setMessage("Sand area successfully detected");
ofLogVerbose("KinectProjector") << "updateROIFromDepthImage(): final kinectROI : " << kinectROI ;
setNewKinectROI();
if (calibrationState == CALIBRATION_STATE_ROI_AUTO_DETERMINATION)
{
applicationState = APPLICATION_STATE_SETUP;
// calibrating = false;
calibModal->hide();
updateStatusGUI();
}
}
ROICalibState = ROI_CALIBRATION_STATE_DONE;
} else if (ROICalibState == ROI_CALIBRATION_STATE_DONE){
}
}
void KinectProjector::updateROIFromFile()
{
string settingsFile = "settings/kinectProjectorSettings.xml";
ofXml xml;
if (xml.load(settingsFile))
{
xml.setTo("KINECTSETTINGS");
kinectROI = xml.getValue<ofRectangle>("kinectROI");
setNewKinectROI();
ROICalibState = ROI_CALIBRATION_STATE_DONE;
return;
}
ofLogVerbose("KinectProjector") << "updateROIFromFile(): could not read settings/kinectProjectorSettings.xml";
applicationState = APPLICATION_STATE_SETUP;
updateStatusGUI();
}
void KinectProjector::setMaxKinectGrabberROI(){
updateKinectGrabberROI(ofRectangle(0, 0, kinectRes.x, kinectRes.y));
}
void KinectProjector::setNewKinectROI()
{
CheckAndNormalizeKinectROI();
// Cast to integer values
kinectROI.x = static_cast<int>(kinectROI.x);
kinectROI.y = static_cast<int>(kinectROI.y);
kinectROI.width = static_cast<int>(kinectROI.width);
kinectROI.height = static_cast<int>(kinectROI.height);
ofLogVerbose("KinectProjector") << "setNewKinectROI : " << kinectROI;
// Update states variables
ROIcalibrated = true;
// ROIUpdated = true;
saveCalibrationAndSettings();
updateKinectGrabberROI(kinectROI);
updateStatusGUI();
}
void KinectProjector::updateKinectGrabberROI(ofRectangle ROI){
kinectgrabber.performInThread([ROI](KinectGrabber & kg) {
kg.setKinectROI(ROI);
});
// while (kinectgrabber.isImageStabilized()){
// } // Wait for kinectgrabber to reset buffers
imageStabilized = false; // Now we can wait for a clean new depth frame
}
std::string KinectProjector::GetTimeAndDateString()
{
time_t t = time(0); // get time now
struct tm * now = localtime(&t);
std::stringstream ss;
ss << now->tm_mday << '-'
<< (now->tm_mon + 1) << '-'
<< (now->tm_year + 1900) << '-'
<< now->tm_hour << '-'
<< now->tm_min << '-'
<< now->tm_sec;
return ss.str();
}
bool KinectProjector::savePointPair()
{
std::string ppK = ofToDataPath(DebugFileOutDir + "CalibrationPointPairsKinect.txt");
std::string ppP = ofToDataPath(DebugFileOutDir + "CalibrationPointPairsKinect.txt");
std::ofstream ppKo(ppK);
std::ofstream ppPo(ppP);
for (int i = 0; i < pairsKinect.size(); i++)
{
ppKo << pairsKinect[i].x << " " << pairsKinect[i].y << " " << pairsKinect[i].z << " " << i << std::endl;
}
for (int i = 0; i < pairsProjector.size(); i++)
{
ppPo << pairsProjector[i].x << " " << pairsProjector[i].y << " " << i << std::endl;
}
return true;
}
void KinectProjector::updateProjKinectAutoCalibration()
{
if (autoCalibState == AUTOCALIB_STATE_INIT_FIRST_PLANE)
{
kinectgrabber.performInThread([](KinectGrabber & kg) {
kg.setMaxOffset(0);
});
calibrationText = "Stabilizing acquisition";
autoCalibState = AUTOCALIB_STATE_INIT_POINT;
updateStatusGUI();
}
else if (autoCalibState == AUTOCALIB_STATE_INIT_POINT && imageStabilized)
{
calibrationText = "Acquiring sea level plane";
updateStatusGUI();
updateBasePlane(); // Find base plane
if (!basePlaneComputed)
{
applicationState = APPLICATION_STATE_SETUP;
calibrationText = "Failed to acquire sea level plane";
updateStatusGUI();
return;
}
calibrationText = "Sea level plane estimated";
updateStatusGUI();
autoCalibPts = new ofPoint[10];
float cs = 4 * chessboardSize / 3;
float css = 3 * chessboardSize / 4;
ofPoint sc = ofPoint(projRes.x/2,projRes.y/2);
// Prepare 10 locations for the calibration chessboard
// With a point of (0,0) the chessboard will be placed with the center in the center of the projector
// a point of -sc will the chessboard will be placed with the center in the upper left corner
// Rasmus modified sequence with a center chessboard first to check if everything is working
autoCalibPts[0] = ofPoint(0 ,0); // Center
autoCalibPts[1] = ofPoint(projRes.x-cs, cs) - sc; // upper right
autoCalibPts[2] = ofPoint(projRes.x-cs, projRes.y-cs) - sc; // Lower right
autoCalibPts[3] = ofPoint( cs, projRes.y-cs) - sc; // Lower left
autoCalibPts[4] = ofPoint( cs, cs) -sc; // upper left
autoCalibPts[5] = ofPoint(0 ,0); // Center
autoCalibPts[6] = ofPoint(projRes.x-css, css) - sc; // upper right
autoCalibPts[7] = ofPoint(projRes.x-css,projRes.y-css) -sc; // Lower right
autoCalibPts[8] = ofPoint(css ,projRes.y-css) -sc; // Lower left
autoCalibPts[9] = ofPoint(css, css) - sc; // upper left
currentCalibPts = 0;
upframe = false;
trials = 0;
TemporalFrameCounter = 0;
ofPoint dispPt = ofPoint(projRes.x / 2, projRes.y / 2) + autoCalibPts[currentCalibPts]; //
drawChessboard(dispPt.x, dispPt.y, chessboardSize); // We can now draw the next chess board
autoCalibState = AUTOCALIB_STATE_NEXT_POINT;
}
else if (autoCalibState == AUTOCALIB_STATE_NEXT_POINT && imageStabilized)
{
if (!(TemporalFrameCounter % 20))
ofLogVerbose("KinectProjector") << "autoCalib(): Got frame " + ofToString(TemporalFrameCounter) + " / " + ofToString(TemporalFrameFilter.getBufferSize() + 3) + " for temporal filter";
// We want to have a buffer of images that are only focusing on one chess pattern
if (TemporalFrameCounter++ > TemporalFrameFilter.getBufferSize() + 3)
{
CalibrateNextPoint();
TemporalFrameCounter = 0;
}
}
else if (autoCalibState == AUTOCALIB_STATE_COMPUTE)
{
updateKinectGrabberROI(kinectROI); // Goes back to kinectROI and maxoffset
kinectgrabber.performInThread([this](KinectGrabber & kg) {
kg.setMaxOffset(this->maxOffset);
});
if (pairsKinect.size() == 0) {
ofLogVerbose("KinectProjector") << "autoCalib(): Error: No points acquired !!" ;
calibrationText = "Calibration failed: No points acquired";
applicationState = APPLICATION_STATE_SETUP;
updateStatusGUI();
}
else
{
ofLogVerbose("KinectProjector") << "autoCalib(): Calibrating" ;
kpt->calibrate(pairsKinect, pairsProjector);
kinectProjMatrix = kpt->getProjectionMatrix();
double ReprojectionError = ComputeReprojectionError(DumpDebugFiles);
ofLogVerbose("KinectProjector") << "autoCalib(): ReprojectionError " + ofToString(ReprojectionError);
if (ReprojectionError > 50)
{
ofLogVerbose("KinectProjector") << "autoCalib(): ReprojectionError too big. Something wrong with projection matrix";
projKinectCalibrated = false;
projKinectCalibrationUpdated = false;
applicationState = APPLICATION_STATE_SETUP;
calibrationText = "Calibration failed - reprojection error too big";
updateStatusGUI();
return;
}
// Rasmus update - I am not sure it is good to override the manual ROI
// updateROIFromCalibration(); // Compute the limite of the ROI according to the projected area
projKinectCalibrated = true; // Update states variables
projKinectCalibrationUpdated = true;
applicationState = APPLICATION_STATE_SETUP;
calibrationText = "Calibration successful";
//saveCalibrationAndSettings(); // Already done in updateROIFromCalibration
if (kpt->saveCalibration("settings/calibration.xml"))
{
ofLogVerbose("KinectProjector") << "update(): initialisation: Calibration saved ";
}
else {
ofLogVerbose("KinectProjector") << "update(): initialisation: Calibration could not be saved ";
}
updateStatusGUI();
}
autoCalibState = AUTOCALIB_STATE_DONE;
}
else if (!imageStabilized)
{
ofLogVerbose("KinectProjector") << "updateProjKinectAutoCalibration(): image not stabilised";
}
else if (autoCalibState == AUTOCALIB_STATE_DONE)
{
}
}
// Compute the error when using the projection matrix to project calibration Kinect points into Project space
// and comparing with calibration projector points
double KinectProjector::ComputeReprojectionError(bool WriteFile)
{
std::string oErrors = ofToDataPath(DebugFileOutDir + "CalibrationReprojectionErrors_" + GetTimeAndDateString() + ".txt");
double PError = 0;
for (int i = 0; i < pairsKinect.size(); i++)
{
ofVec4f wc = pairsKinect[i];
wc.w = 1;
ofVec4f screenPos = kinectProjMatrix*wc;
ofVec2f projectedPoint(screenPos.x / screenPos.z, screenPos.y / screenPos.z);
ofVec2f projP = pairsProjector[i];
double D = sqrt((projectedPoint.x - projP.x) * (projectedPoint.x - projP.x) + (projectedPoint.y - projP.y) * (projectedPoint.y - projP.y));
PError += D;
}
PError /= (double)pairsKinect.size();
if (WriteFile)
{
std::ofstream fost2(oErrors.c_str());
for (int i = 0; i < pairsKinect.size(); i++)
{
ofVec4f wc = pairsKinect[i];
wc.w = 1;
ofVec4f screenPos = kinectProjMatrix*wc;
ofVec2f projectedPoint(screenPos.x / screenPos.z, screenPos.y / screenPos.z);
ofVec2f projP = pairsProjector[i];
double D = sqrt((projectedPoint.x - projP.x) * (projectedPoint.x - projP.x) + (projectedPoint.y - projP.y) * (projectedPoint.y - projP.y));
fost2 << wc.x << ", " << wc.y << ", " << wc.z << ", "
<< projP.x << ", " << projP.y << ", " << projectedPoint.x << ", " << projectedPoint.y << ", " << D << std::endl;
}
}
return PError;
}
void KinectProjector::CalibrateNextPoint()
{
if (currentCalibPts < 5 || (upframe && currentCalibPts < 10))
{
if (!upframe)
{
calibrationText = "Calibration (low) # " + std::to_string(currentCalibPts + 1) + "/5";
updateStatusGUI();
}
else
{
calibrationText = "Calibration (high) # " + std::to_string(currentCalibPts - 4) + "/5";
updateStatusGUI();
}
// Current RGB frame - probably with rolling shutter problems
cvRgbImage = ofxCv::toCv(kinectColorImage.getPixels());
ofxCvGrayscaleImage tempImage;
if (TemporalFilteringType == 0)
tempImage.setFromPixels(TemporalFrameFilter.getMedianFilteredImage(), kinectColorImage.width, kinectColorImage.height);
if (TemporalFilteringType == 1)
tempImage.setFromPixels(TemporalFrameFilter.getAverageFilteredColImage(), kinectColorImage.width, kinectColorImage.height);
ProcessChessBoardInput(tempImage);
if (DumpDebugFiles)
{
std::string tname = DebugFileOutDir + "ChessboardImage_" + GetTimeAndDateString() + "_" + ofToString(currentCalibPts) + "_try_" + ofToString(trials) + ".png";
ofSaveImage(tempImage.getPixels(), tname);
}
cvGrayImage = ofxCv::toCv(tempImage.getPixels());
cv::Rect tempROI((int)kinectROI.x, (int)kinectROI.y,(int)kinectROI.width, (int)kinectROI.height);
cv::Mat cvGrayROI = cvGrayImage(tempROI);
cv::Size patternSize = cv::Size(chessboardX - 1, chessboardY - 1);
// int chessFlags = cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK;
int chessFlags = 0;
//bool foundChessboard = findChessboardCorners(cvGrayImage, patternSize, cvPoints, chessFlags);
bool foundChessboard = findChessboardCorners(cvGrayROI, patternSize, cvPoints, chessFlags);
if (!foundChessboard)
{
int chessFlags = cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK;
foundChessboard = findChessboardCorners(cvGrayROI, patternSize, cvPoints, chessFlags);
}
// Changed logic so the "cleared" flag is not used - we do a long frame average instead
if (foundChessboard)
{
for (int i = 0; i < cvPoints.size(); i++)
{
cvPoints[i].x += tempROI.x;
cvPoints[i].y += tempROI.y;
}
cornerSubPix(cvGrayImage, cvPoints, cv::Size(2, 2), cv::Size(-1, -1), // Rasmus: changed search size to 2 from 11 - since this caused false findings
cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
drawChessboardCorners(cvRgbImage, patternSize, cv::Mat(cvPoints), foundChessboard);
if (DumpDebugFiles)
{
std::string tname = DebugFileOutDir + "FoundChessboard_" + GetTimeAndDateString() + "_" + ofToString(currentCalibPts) + "_try_" + ofToString(trials) + ".png";
ofSaveImage(kinectColorImage.getPixels(), tname);
}