-
Notifications
You must be signed in to change notification settings - Fork 8
/
kilobottracker.cpp
2922 lines (2314 loc) · 115 KB
/
kilobottracker.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
/*!
* Kilobottracker.cpp
*
* Created on: 3 Oct 2016
* Author: Alex Cope
*/
#include "kilobottracker.h"
#include "kilobotexperiment.h"
#include <QImage>
#include <QThread>
#include <QLineEdit>
#include <QDir>
#include <QSettings>
#include <QFileDialog>
#include <QtMath>
#include <QDebug>
//#define TEST_WITHOUT_CAMERAS
//#define TESTLEDS
#define COLDET_V1
QSemaphore srcFree[4];
QSemaphore srcUsed[4];
srcBuffer srcBuff[4][BUFF_SIZE];
QSemaphore srcStop[4];
QSemaphore camUsage;
int camOrder[4] = {0,1,2,3};
/*!
* \brief The acquireThread class
* This thread acquires input data from a source, applies the local warps
* to the data, and then places the data in a circular buffer for use by
* the main thread, which operates on a QTimer to allow UI responsivity
*/
class acquireThread : public QThread
{
public:
~acquireThread() {
// shut down cam
camUsage.acquire();
if (cap.isOpened()) cap.release();
camUsage.release();
}
// reprojection details
Mat K;
Mat R;
Point corner;
Size size;
Size fullSize;
Point fullCorner;
Point2f arenaCorners[4];
QString videoDir = "";
int height_x_adj;
int height_y_adj;
// the index of the source
uint index = 0;
bool keepRunning = true;
srcDataType type = CAMERA;
cv::VideoCapture cap;
//video saving
bool savecamerasframes=false;
QString videoframeprefix;
private:
/*!
* \brief run
* The execution method for the thread, performing the stitching process
*/
void run() {
QThread::currentThread()->setPriority(QThread::TimeCriticalPriority);
#ifdef USE_OPENCV3
if (ocl::haveOpenCL()) {
ocl::setUseOpenCL(true);
}
#endif
#ifdef USE_CUDA
// if using CUDA we need a stream to make the operations thread safe
cuda::Stream stream;
#endif
uint time = 0;
Mat image;
Mat mask;
Ptr<WarperCreator> warper_creator;
warper_creator = new cv::PlaneWarper();//makePtr<cv::PlaneWarper>();
Ptr<detail::RotationWarper> warper = warper_creator->create(2000.0f);
Point2f outputQuad[4];
outputQuad[0] = Point(0,0);
outputQuad[1] = Point(2000,0);
outputQuad[2] = Point(0,2000);
outputQuad[3] = Point(2000,2000);
// loop
while (keepRunning) {
// check for stop signal
if (srcStop[index].available()) {
keepRunning = false;
}
if (srcFree[index].available()) {
// get data
if (type == IMAGES) {
// NOTE: need to decide on format for imagevideos
image = imread((this->videoDir+QDir::toNativeSeparators("/")+QString("frame_00200_")+QString::number(index)+QString(".jpg")).toStdString());
}
else if (type == CAMERA) {
#ifndef TEST_WITHOUT_CAMERAS
// Open the camera
camUsage.acquire();
if (!cap.isOpened() && camOrder[index]<4) {
cap.open(camOrder[index]);
// set REZ
if (cap.isOpened()) {
cap.set(CV_CAP_PROP_FOURCC, CV_FOURCC('M','J','P','G'));
cap.set(CV_CAP_PROP_FRAME_WIDTH, IM_WIDTH);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, IM_HEIGHT);
} else {
this->keepRunning = false;
continue;
}
}
if (cap.isOpened()) {
// exhaust buffer
cap.grab();
cap.grab();
camUsage.release();
camUsage.acquire();
cap.retrieve(image);
if(savecamerasframes) {
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
imwrite(videoframeprefix.toStdString(), image, compression_params);
savecamerasframes=false;
}
camUsage.release();
}
else
#endif
{
image = Mat(IM_HEIGHT,IM_WIDTH, CV_8UC3, Scalar(0,0,0)); /* TEMPORARY!!! */
camUsage.release();
}
} else if (type == VIDEO) {
qDebug() << (this->videoDir+QDir::toNativeSeparators("/")+QString("frame_%1_%2").arg(/*time+*/time, 5,10, QChar('0')).arg(index)+QString(".jpg"));
image = imread((this->videoDir+QDir::toNativeSeparators("/")+QString("frame_%1_%2").arg(/*time+*/time, 5,10, QChar('0')).arg(index)+QString(".jpg")).toStdString());
if (image.empty()) {qDebug() << "Image not found"; continue;}
}
// Prepare images masks
if (mask.size().width < 10) {
mask.create(image.size(), CV_8U);
}
mask.setTo(Scalar::all(255));
// check semaphore
srcFree[index].acquire();
#ifdef USE_CUDA
Mat tempCuda;
srcBuff[index][time % BUFF_SIZE].corner = warper->warp(image, K, R, INTER_LINEAR, BORDER_REFLECT, tempCuda);
srcBuff[index][time % BUFF_SIZE].warped_image.upload(tempCuda);
srcBuff[index][time % BUFF_SIZE].size = srcBuff[index][time % BUFF_SIZE].warped_image.size();
warper->warp(mask, K, R, INTER_NEAREST, BORDER_CONSTANT, tempCuda);
srcBuff[index][time % BUFF_SIZE].warped_mask.upload(tempCuda);
#else
srcBuff[index][time % BUFF_SIZE].corner = warper->warp(image, K, R, INTER_LINEAR, BORDER_REFLECT, srcBuff[index][time % BUFF_SIZE].warped_image);
srcBuff[index][time % BUFF_SIZE].size = srcBuff[index][time % BUFF_SIZE].warped_image.size();
warper->warp(mask, K, R, INTER_NEAREST, BORDER_CONSTANT, srcBuff[index][time % BUFF_SIZE].warped_mask);
#endif
// only do this if we are not loading calibration
if (!(this->corner.x == -1 && this->corner.y == -1)) {
// adjustment used to compensate for placing calibration images on table, and not at kilobot height
MAT_TYPE temp;
#ifdef USE_CUDA
// qDebug() << "Size w: " << size.width << " h: " << size.height;
// qDebug() << "Full-Size w: " << fullSize.width << " h: " << fullSize.height;
// cv::cuda::resize(srcBuff[index][time % BUFF_SIZE].warped_image, temp, Size(size.width-height_adj,size.height-height_adj),0,0, INTER_LINEAR, stream);
// cv::cuda::resize(temp, temp2,Size((2048*(size.width-height_adj))/fullSize.width,(1536*(size.height-height_adj))/fullSize.height),0,0, INTER_LINEAR, stream);
cv::cuda::resize(srcBuff[index][time % BUFF_SIZE].warped_image, temp, Size((min(IM_HEIGHT,IM_WIDTH)*(size.width-height_x_adj))/fullSize.width,(min(IM_HEIGHT,IM_WIDTH)*(size.height-height_y_adj))/fullSize.height),0,0, INTER_LINEAR, stream);
#else
cv::resize(srcBuff[index][time % BUFF_SIZE].warped_image, temp,Size((min(IM_HEIGHT,IM_WIDTH)*(size.width-height_x_adj))/fullSize.width,(min(IM_HEIGHT,IM_WIDTH)*(size.height-height_y_adj))/fullSize.height));
#endif
Point2f arenaCorners_adj[4];
Point2f outputQuad_adj[4];
// qDebug() << "Thread " << this->index << " corner " << corner.x << "," << corner.y << " full Corner " << fullCorner.x << "," << fullCorner.y;
for (int i = 0; i < 4; ++i) {
arenaCorners_adj[i] = arenaCorners[i] - Point2f(((corner.x-fullCorner.x)*min(IM_HEIGHT,IM_WIDTH))/fullSize.width,((corner.y-fullCorner.y)*min(IM_HEIGHT,IM_WIDTH))/fullSize.height);
// qDebug() << "arenaCorners_adj " << i << " is " << arenaCorners_adj[i].x << "," << arenaCorners_adj[i].y;
// shift the location for all but the first camera, and add 100 pixel overlap around the images
outputQuad_adj[i] = outputQuad[i] - Point2f((fabs(corner.x-fullCorner.x)>100)*1000-100, (fabs(corner.y-fullCorner.y)>100)*1000-100);
}
Mat M = getPerspectiveTransform(arenaCorners_adj,outputQuad_adj);
// 1200 x 1200 output includes 100 pixel overlap aound entire image
#ifdef USE_CUDA
cuda::warpPerspective(temp, srcBuff[index][time % BUFF_SIZE].full_warped_image, M, Size(1200,1200),INTER_LINEAR,BORDER_CONSTANT,Scalar(),stream);
#else
warpPerspective(temp, srcBuff[index][time % BUFF_SIZE].full_warped_image, M, Size(1200,1200));
#endif
}
srcUsed[index].release();
++time;
}
}
QThread::currentThread()->setPriority(QThread::NormalPriority);
}
};
KilobotTracker::KilobotTracker(QPoint smallImageSize, QObject *parent) : QObject(parent)
{
// select cuda device
#ifdef USE_CUDA
//qDebug() << "There are" << cuda::getCudaEnabledDeviceCount() << "CUDA devices";
try {
cuda::setDevice(cuda::getCudaEnabledDeviceCount()-2);
} catch (cv::Exception){
cuda::setDevice(cuda::getCudaEnabledDeviceCount()-1);
}
qDebug() << "Using CUDA device " << cuda::DeviceInfo().name();
#endif
this->smallImageSize = smallImageSize;
this->tick.setInterval(1);
connect(&this->tick, SIGNAL(timeout()), this, SLOT(LOOPiterate()));
// initialise semaphores
srcFree[0].release(BUFF_SIZE);
srcFree[1].release(BUFF_SIZE);
srcFree[2].release(BUFF_SIZE);
srcFree[3].release(BUFF_SIZE);
camUsage.release(1);
}
KilobotTracker::~KilobotTracker()
{
if (this->threads[0] && this->threads[0]->isRunning()) {
this->THREADSstop();
}
// clean up memory
for (uint i = 0; i < 4; ++i) {
if (this->threads[i]) {
delete this->threads[i];
}
}
}
void KilobotTracker::LOOPstartstop(int expType)
{
this->expType = (experimentType) expType;
// update the run/stop button
emit toggleExpButton((int)expType);
// check if running
if (this->threads[0] && this->threads[0]->isRunning()) {
// reset IDing
//this->aStage = START;
currentID = 0;
emit errorMessage(QString("FPS = ") + QString::number(float(time)/(float(timer.elapsed())/1000.0f)));
this->THREADSstop();
// Stop the experiment
if (this->expType != IDENTIFY) {
emit stopExperiment();
}
QThread::currentThread()->setPriority(QThread::NormalPriority);
// Reset the time to zero for the next experiment
time=0;
return;
}
emit clearMsgQueue();
#ifdef USE_CUDA
// setup kb initial locs
Mat tempKbLocs(1,kilos.size(), CV_32FC2);
float * data = (float *) tempKbLocs.data;
for (int i = 0; i < kilos.size(); ++i) {
data[i*2] = kilos[i]->getPosition().x();
data[i*2+1] = kilos[i]->getPosition().y();
}
kbLocs.upload(tempKbLocs);
//this->hough = cuda::createHoughCirclesDetector(1.0,1.0,this->cannyThresh,this->houghAcc,this->kbMinSize,this->kbMaxSize,5000); // kilobot detection
//this->hough = cuda::createHoughCirclesDetector(1.0,this->kbMinSize/1.4,this->cannyThresh,this->houghAcc,this->kbMinSize,this->kbMaxSize,3000); // kilobot detection
this->hough = cuda::createHoughCirclesDetector(1.0,1.0,this->cannyThresh,this->houghAcc,this->kbMinSize,this->kbMaxSize,20000); // kilobot detection
this->hough2 = cuda::createHoughCirclesDetector(1.0,1.0,this->cannyThresh,this->houghAcc,this->kbMinSize/7,this->kbMinSize*10/7,10000);// led detection
//this->hough2 = cuda::createHoughCirclesDetector(1.0,1.0,this->cannyThresh,this->houghAcc,1,this->kbMinSize*10/7,10000);// led detection
clahe=cuda::createCLAHE(10);
dilateFilter=cuda::createMorphologyFilter(MORPH_DILATE,CV_8UC1, element);
#endif
QThread::currentThread()->setPriority(QThread::TimeCriticalPriority);
// only if we have calib data
if (!this->haveCalibration) {
return;
}
// when the ID-ASSIGNMENT starts, new sequential (random) IDs are assigned to each ARK-Kilobot at the start of the process (to avoid duplicates)
if (this->expType == ID_ASSIGNMENT){
for (int i = 0; i < this->kilos.size(); ++i) {
this->kilos[i]->setID(i);
}
}
// launch threads
this->THREADSlaunch();
// connect kilobots
for (int i = 0; i < this->kilos.size(); ++i) {
this->kilos[i]->disconnect(SIGNAL(sendUpdateToExperiment(Kilobot*,Kilobot)));
connect(this->kilos[i],SIGNAL(sendUpdateToExperiment(Kilobot*,Kilobot)), this->expt, SLOT(setupInitialStateRequiredCode(Kilobot*,Kilobot)));
}
/** @Salah: check if the compensator and blender is ever used */
if (!this->compensator) {
// calculate to compensate for exposure
compensator = detail::ExposureCompensator::createDefault(detail::ExposureCompensator::GAIN);
}
if (!this->blender) {
// blend the images
blender = detail::Blender::createDefault(detail::Blender::FEATHER, true);
}
this->warpedImages.resize(4);
this->warpedMasks.resize(4);
this->corners.resize(4);
this->sizes.resize(4);
currentID = 0;
// start timer
this->time = 0;
this->last_time = 0.0f;
this->tick.start();
this->timer.start();
// reset tracking vectors
this->lost_count.clear();
this->lost_count.resize(this->kilos.size());
this->pendingRuntimeIdentification.clear();
this->m_ongoingRuntimeIdentification = false;
this->m_runtimeIdentificationTimer = 0;
}
void KilobotTracker::LOOPiterate()
{
if(savecamerasframes && (time <= numberofframes)){
if(!(this->threads[0]->savecamerasframes) &&
!(this->threads[1]->savecamerasframes) &&
!(this->threads[2]->savecamerasframes) &&
!(this->threads[3]->savecamerasframes)){
for (uint i = 0; i < 4; ++i)
{
this->threads[i]->savecamerasframes = true;
this->threads[i]->videoframeprefix=savecamerasframesdir+QString("/")+QString("frame_%1_%2").arg(/*time+*/time-1, 5,10, QChar('0')).arg(i)+QString(".jpg");
}
}
else return;
}
else savecamerasframes=false;
// wait for semaphores
if ((srcUsed[0].available() > 0 && \
srcUsed[1].available() > 0 && \
srcUsed[2].available() > 0 && \
srcUsed[3].available() > 0) || this->loadFirstIm)
{
// we have tracking, so it is safe to start the experiment
if (!this->loadFirstIm && time == 0) {
if (this->expType != IDENTIFY) {
emit startExperiment(false /*we are not resuming the experiment*/);
}
}
srcUsed[0].acquire();
srcUsed[1].acquire();
srcUsed[2].acquire();
srcUsed[3].acquire();
// process images into single image
for (uint i = 0; i < 4; ++i) {
this->warpedImages[i] = srcBuff[i][time % BUFF_SIZE].warped_image;
this->warpedMasks[i] = srcBuff[i][time % BUFF_SIZE].warped_mask;
this->corners[i] = srcBuff[i][time % BUFF_SIZE].corner;
this->sizes[i] = srcBuff[i][time % BUFF_SIZE].size;
}
// feed with first frame
#ifndef USE_CUDA
if (time == 0) {
compensator->feed(corners, warpedImages, warpedMasks);
}
// apply compensation
for (int i = 0; i < 4; ++i) {
compensator->apply(i, corners[i], srcBuff[i][time % BUFF_SIZE].full_warped_image, warpedMasks[i]);
}
#endif
#ifdef USE_CUDA
cuda::GpuMat channels[4][3];
#else
Mat channels[4][3];
#endif
Mat saveIm[4];
// move full images from threads
for (uint i = 0; i < 4; ++i) {
#ifdef USE_CUDA
cuda::GpuMat temp;
#else
Mat temp;
#endif
srcBuff[i][time % BUFF_SIZE].full_warped_image.copyTo(temp);
CV_NS split(temp, channels[i]);
#ifdef USE_CUDA
temp.download(saveIm[i]);
#else
saveIm[i] = temp;
#endif
this->fullImages[i][0] = channels[i][0];
this->fullImages[i][1] = channels[i][1];
this->fullImages[i][2] = channels[i][2];
}
Mat top;
Mat bottom;
#ifdef USE_CUDA
cv::cuda::GpuMat resultB(2000, 2000, this->fullImages[clData.inds[0]][0].type());
this->fullImages[clData.inds[0]][0](Rect(100,100,1000,1000)).copyTo(resultB(cv::Rect(0,0,1000,1000)));
this->fullImages[clData.inds[1]][0](Rect(100,100,1000,1000)).copyTo(resultB(cv::Rect(1000,0,1000,1000)));
this->fullImages[clData.inds[2]][0](Rect(100,100,1000,1000)).copyTo(resultB(cv::Rect(0,1000,1000,1000)));
this->fullImages[clData.inds[3]][0](Rect(100,100,1000,1000)).copyTo(resultB(cv::Rect(1000,1000,1000,1000)));
cv::cuda::GpuMat resultG(2000, 2000, this->fullImages[clData.inds[0]][0].type());
this->fullImages[clData.inds[0]][1](Rect(100,100,1000,1000)).copyTo(resultG(cv::Rect(0,0,1000,1000)));
this->fullImages[clData.inds[1]][1](Rect(100,100,1000,1000)).copyTo(resultG(cv::Rect(1000,0,1000,1000)));
this->fullImages[clData.inds[2]][1](Rect(100,100,1000,1000)).copyTo(resultG(cv::Rect(0,1000,1000,1000)));
this->fullImages[clData.inds[3]][1](Rect(100,100,1000,1000)).copyTo(resultG(cv::Rect(1000,1000,1000,1000)));
cv::cuda::GpuMat resultR(2000, 2000, this->fullImages[clData.inds[0]][0].type());
this->fullImages[clData.inds[0]][2](Rect(100,100,1000,1000)).copyTo(resultR(cv::Rect(0,0,1000,1000)));
this->fullImages[clData.inds[1]][2](Rect(100,100,1000,1000)).copyTo(resultR(cv::Rect(1000,0,1000,1000)));
this->fullImages[clData.inds[2]][2](Rect(100,100,1000,1000)).copyTo(resultR(cv::Rect(0,1000,1000,1000)));
this->fullImages[clData.inds[3]][2](Rect(100,100,1000,1000)).copyTo(resultR(cv::Rect(1000,1000,1000,1000)));
#else
Mat result;
hconcat(this->fullImages[clData.inds[0]][0](Rect(100,100,1000,1000)),this->fullImages[clData.inds[1]][0](Rect(100,100,1000,1000)),top);
hconcat(this->fullImages[clData.inds[2]][0](Rect(100,100,1000,1000)),this->fullImages[clData.inds[3]][0](Rect(100,100,1000,1000)),bottom);
vconcat(top,bottom,result);
#endif
hconcat(saveIm[clData.inds[0]](Rect(100,100,1000,1000)),saveIm[clData.inds[1]](Rect(100,100,1000,1000)),top);
hconcat(saveIm[clData.inds[2]](Rect(100,100,1000,1000)),saveIm[clData.inds[3]](Rect(100,100,1000,1000)),bottom);
vconcat(top,bottom,this->finalImageCol);
srcFree[0].release();
srcFree[1].release();
srcFree[2].release();
srcFree[3].release();
if (flipangle!=0) {
cv::Point origin(this->finalImageB.cols/2,this->finalImageB.rows/2);
Mat rotationmatrixCPU;
rotationmatrixCPU=getRotationMatrix2D(origin,flipangle,1);
cuda::warpAffine(resultB,this->finalImageB,rotationmatrixCPU,resultB.size());
cuda::warpAffine(resultG,this->finalImageG,rotationmatrixCPU,resultG.size());
cuda::warpAffine(resultR,this->finalImageR,rotationmatrixCPU,resultR.size());
} else {
this->finalImageB = resultB;
this->finalImageG = resultG;
this->finalImageR = resultR;
}
switch (this->expType) {
case USER_EXP:{
this->trackKilobots();
/** determine if executing the runtime-identification (RTI) */
if (this->m_runtimeIDenabled && !experimentIsBroadcasting)
{
bool runRTI = false;
if (this->m_ongoingRuntimeIdentification){ // if already running, keep running
runRTI = true;
} else if (!this->pendingRuntimeIdentification.empty() && this->m_runtimeIdentificationTimer++ > 50){ // if there are pending request for more than 5s
// I check that all pending request are not lost robots
bool anyLost = false;
for (int i=0; i<this->pendingRuntimeIdentification.size(); ++i){
if (this->lost_count[this->pendingRuntimeIdentification[i]] > 0){
anyLost = true;
break;
}
}
if (anyLost)
this->m_runtimeIdentificationTimer -= 10; // delay the timer if there are lost robot (otherwise as soon it has been found it starts)
else
runRTI = true;
}
if (runRTI) runtimeIdentify();
}
break;
}
case IDENTIFY:{
this->identifyKilobots();
break;
}
default:{
this->trackKilobots();
break;
}
}
++time;
if (time % 5 == 0) {
float c_time = float(this->timer.elapsed())/1000.0f;
emit errorMessage(QString("FPS = ") + QString::number(5.0f/(c_time-last_time)));
last_time = c_time;
}
}
}
void KilobotTracker::runtimeIdentify(){
//qDebug() << "Runtime-ID: " << this->m_runtimeIdentificationTimer;
if (!this->m_ongoingRuntimeIdentification) {
qDebug() << "Runtime-ID: started for robots" << this->pendingRuntimeIdentification;
emit setRuntimeIdentificationLock(true);
this->m_ongoingRuntimeIdentification = true;
this->runtimeIDtimer.start();
// Reset lists and counters
this->m_runtimeIdentificationTimer = 0;
this->foundIDs.clear();
this->currentID = 0;
// broadcast ID
identifyKilobot(this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID(), true);
qDebug() << "Runtime-ID: Signalled ID" << this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID();
}
//#ifdef USE_CUDA
// Mat display;
// this->finalImageB.download(display);
// cv::cvtColor(display, display, CV_GRAY2RGB);
//#else
// Mat display;
// cv::cvtColor(this->finalImage, display, CV_GRAY2RGB);
//#endif
// this->getKiloBotLights(display);
if(this->m_runtimeIdentificationTimer++ >= 10) {
this->m_runtimeIdentificationTimer = 0;
int blueBots = 0;
int bot = -1;
// I allow only swaps between robots on the pending list, if there is some false detect I update the list
for (int i = 0; i < this->pendingRuntimeIdentification.size(); ++i) {
// if (this->kilos[this->pendingRuntimeIdentification[i]]->getLedColour() == BLUE) {
if (this->lost_count[this->pendingRuntimeIdentification[i]] < 10 && this->kilos[this->pendingRuntimeIdentification[i]]->getLedColour() == BLUE) {
qDebug() << "Runtime-ID: found blue LED robot #" << this->kilos[this->pendingRuntimeIdentification[i]]->getID();
blueBots++;
bot = this->pendingRuntimeIdentification[i];
}
}
if (blueBots == 1){
//kilos[bot]->setID((uint8_t) currentID);
//this->circsToDraw.push_back(drawnCircle {Point(kilos[bot]->getPosition().x(),kilos[bot]->getPosition().y()), 4, QColor(0,255,0), 2, ""});
this->foundIDs.push_back(this->currentID);
qDebug() << "Looking for position " << this->pendingRuntimeIdentification[this->currentID] << " (id:"<<this->kilos[this->pendingRuntimeIdentification[currentID]]->getID()<<")"<<
"and found position" << bot << " (id:"<<this->kilos[bot]->getID()<<")";
if (this->pendingRuntimeIdentification[this->currentID] == bot) {
qDebug() << "Runtime-ID: Kilobot #" << this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID() << "was correctly assigned";
} else {
// swapping robot positions (otherwise I lose the robot tracking)
qDebug() << "Runtime-ID: reassignment!! Kilobot #" << this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID() << "moved to new location.";
QPointF tmpPos = this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getPosition();
QPointF tmpVel = this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getVelocity();
kilobot_colour tmpCol = this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getLedColour();
this->kilos[this->pendingRuntimeIdentification[this->currentID]]->updateState(
QPointF(this->kilos[bot]->getPosition().x(),this->kilos[bot]->getPosition().y()),
this->kilos[bot]->getVelocity(),this->kilos[bot]->getLedColour() );
this->kilos[bot]->updateState( tmpPos, tmpVel, tmpCol );
// re-upload locations on GPU
Mat tempKbLocs(1,this->kilos.size(), CV_32FC2);
float * data = (float *) tempKbLocs.data;
for (int i = 0; i < this->kilos.size(); ++i) {
data[i*2] = this->kilos[i]->getPosition().x();
data[i*2+1] = this->kilos[i]->getPosition().y();
}
this->kbLocs.upload(tempKbLocs);
}
} else if (blueBots > 1) {
qDebug() << "Runtime-ID: Multiple detections. ID n." << this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID() << "has not been re-assigned";
} else if (blueBots < 1) {
qDebug() << "Runtime-ID: No bot found for ID n." << this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID() << "in the pending list";
blueBots = 0;
bot = -1;
for (int i = 0; i < this->kilos.size(); ++i) {
if (this->kilos[i]->getLedColour() == BLUE) {
blueBots++;
bot = i;
qDebug() << "Runtime-ID: Found robot #" << kilos[i]->getID() << "with blue LED. Added to pending for runtime identification";
if (!this->pendingRuntimeIdentification.contains(i)) this->pendingRuntimeIdentification.push_back(i);
}
}
if (!blueBots) qDebug() << "No Blue response from all the swarm.";
}
if (this->foundIDs.size() == this->pendingRuntimeIdentification.size() ) { // all robots has been found
// || currentID == this->pendingRuntimeIdentification.size()-2 ) { OR I looped through all
qDebug() << "Runtime-ID: All" << this->foundIDs.size() << "robots have been correcly runtime-identified.";
// clearing pending list
this->pendingRuntimeIdentification.clear();
this->foundIDs.clear();
this->m_runtimeIdentificationTimer = 0;
// stopping the runtime identification process
this->m_ongoingRuntimeIdentification = false;
// inform the experiment the runtime ID has stopped
emit setRuntimeIdentificationLock(false);
// inform the kilobots
identifyKilobot(-1, true);
}
else { // next id
this->currentID++;
while( this->foundIDs.contains(this->currentID) || this->currentID >= this->pendingRuntimeIdentification.size() ){
if (++this->currentID >= this->pendingRuntimeIdentification.size()) this->currentID = 0;
}
identifyKilobot(this->kilos[this->pendingRuntimeIdentification[this->currentID]]->getID(), true);
qDebug() << "Runtime-ID: Signalled ID" << this->kilos[this->pendingRuntimeIdentification[currentID]]->getID();
// setting maximum time allowed for runtime ID identification
//int maxTimeForRuntimeID = (this->pendingRuntimeIdentification.size() < 6)? 10000 : this->pendingRuntimeIdentification.size() * 2000;
int maxTimeForRuntimeID = qMax<int>(30000,1000*5*this->pendingRuntimeIdentification.size());
// check if I am trying identifying on lost robots
for (int i = 0; i < this->pendingRuntimeIdentification.size(); ++i) {
/* if a missing robot has been lost for more than 10 step, the runtime identification is stopped but pending list only partially cleared */
/* also stop if the process is running for more than 10s */
if (!this->foundIDs.contains(i) && this->lost_count[this->pendingRuntimeIdentification[i]] > 10 || this->runtimeIDtimer.elapsed() > maxTimeForRuntimeID ){
qDebug() << "Runtime-ID: Giving up runtime identification because involves lost robots or it's taking too much time, e.g. robot #" << this->kilos[this->pendingRuntimeIdentification[i]]->getID();
this->foundIDs.clear();
this->m_runtimeIdentificationTimer = -50;
// stopping the runtime identification process
this->m_ongoingRuntimeIdentification = false;
// inform the experiment the runtime ID has stopped
emit setRuntimeIdentificationLock(false);
// inform the kilobots
identifyKilobot(-1, true);
}
}
}
}
//this->drawOverlay(display);
//this->showMat(display);
}
void KilobotTracker::updateKilobotStates()
{
for (int i = 0; i < kilos.size(); ++i) {
kilos[i]->updateExperiment();
kilos[i]->updateHardware();
}
}
void KilobotTracker::getInitialKilobotStates()
{
for (int i = 0; i < kilos.size(); ++i) {
kilos[i]->updateExperiment();
}
}
void KilobotTracker::SETUPfindKilobots()
{
if (this->finalImageB.empty()) return;
Mat res2;
Mat display;
#ifdef USE_CUDA
this->finalImageB.download(display);
display.copyTo(res2);
#else
this->finalImage.copyTo(display);
res2 = this->finalImage;
#endif
vector<Vec3f> circles;
HoughCircles(res2,circles,CV_HOUGH_GRADIENT,1.0/* rez scaling (1 = full rez, 2 = half etc)*/ \
,this->kbMaxSize-1/* circle distance*/ \
,cannyThresh /* Canny threshold*/ \
,houghAcc /*cicle algorithm accuracy*/ \
,kbMinSize/* min circle size*/ \
,kbMaxSize/* max circle size*/);
// the *2 is an assumption - should always be true...
cv::cvtColor(display, display, CV_GRAY2RGB);
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// draw the circle center
//circle( result, center, 3, Scalar(0,255,0), -1, 8, 0 );
// draw the circle outline
circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 );
putText(display, this->showIDs?to_string(i):"", center, FONT_HERSHEY_PLAIN, 2.7, Scalar(0,0,255), 3);
}
cv::resize(display,display,Size(this->smallImageSize.x()*2, this->smallImageSize.y()*2));
// convert to C header for easier mem ptr addressing
IplImage imageIpl = display;
// create a QImage container pointing to the image data
QImage qimg((uchar *) imageIpl.imageData,imageIpl.width,imageIpl.height,QImage::Format_RGB888);
// assign to a QPixmap (may copy)
QPixmap pix = QPixmap::fromImage(qimg);
setStitchedImage(pix);
// generate kilobots
this->kilos.clear();
kilobot_colour col = OFF;
for( size_t i = 0; i < circles.size(); i++ ) {
this->kilos.push_back(new Kilobot(i,QPointF(circles[i][0],circles[i][1]),QPointF(1,1),col));
}
this->kiloHeadings.clear();
this->kiloHeadings.resize(this->kilos.size());
emit errorMessage(QString::fromStdString(to_string(kilos.size()))+ QString(" kilobots found!"));
emit activateExpButtons(this->kilos.size());
}
void KilobotTracker::identifyKilobots()
{
if (this->kilos.isEmpty()){
qDebug() << "There are no Kilobots to be indetified. Stopping the operation";
LOOPstartstop(IDENTIFY);
return;
}
#ifdef USE_CUDA
Mat display;
this->finalImageB.download(display);
cv::cvtColor(display, display, CV_GRAY2RGB);
#else
Mat display;
cv::cvtColor(this->finalImage, display, CV_GRAY2RGB);
#endif
if (time == 0)
{
qDebug() << "Max ID to test is" << maxIDtoCheck;
// check that max id is higher than number of tracked kilobots
if (maxIDtoCheck < qMax(0,kilos.size()-2)){
qDebug() << "ERROR! More robots than possible IDs. Change the max ID to test (currently it's" << maxIDtoCheck << ")";
return;
}
// Reset lists and counters
currentID = 0;
foundIDs.clear();
assignedCircles.clear();
this->circsToDraw.clear();
this->linesToDraw.clear();
// broadcast ID
identifyKilobot(currentID);
qDebug() << "Try ID" << currentID;
}
// Restart from current ID=0 if we reached MaxIDtoCheck
if (currentID > maxIDtoCheck){
currentID = 0;
while( foundIDs.contains(currentID) ){
currentID++;
}
// broadcast ID
identifyKilobot(currentID);
qDebug() << "Try ID" << currentID;
}
// broadcast ID
//identifyKilobot(currentID);
this->getKiloBotLights(display);
if(time % 5 == 4)
{
int blueBots = 0;
int bot = -1;
for (uint i = 0; i < (uint) kilos.size(); ++i) {
if (kilos[i]->getLedColour() == BLUE) {
qDebug() << "Found ID" << currentID;
blueBots++;
bot = i;
}
}
if (blueBots == 1 && !assignedCircles.contains(bot)){
kilos[bot]->setID((uint8_t) currentID);
this->circsToDraw.push_back(drawnCircle {Point(kilos[bot]->getPosition().x(),kilos[bot]->getPosition().y()), 4, QColor(0,255,0), 2, ""});
foundIDs.push_back(currentID);
assignedCircles.push_back(bot);
qDebug() << "Success!! ID n." << currentID << " successfully assigned!!";
} else if (blueBots > 1) {
qDebug() << "Multiple detections. ID n." << currentID << " has not been assigned";
} else if (blueBots < 1) {
qDebug() << "No bot found for ID n." << currentID;
} else if (blueBots == 1 && assignedCircles.contains(bot)) {
qDebug() << "Trying to re-assign the same circle to a second ID. I don't make this assigment and I undo the previous, i.e., ID" << kilos[bot]->getID();
foundIDs.removeOne( kilos[bot]->getID() );
assignedCircles.removeOne(bot);
}
if (foundIDs.size() == kilos.size()) { // all robots has been found
qDebug() << "All" << kilos.size() << "robots have been correcly identified. Well Done, mate! Now, it's time for serious stuff.";
this->LOOPstartstop(IDENTIFY);
}
else { // next id
++currentID;
while( foundIDs.contains(currentID) ){
currentID++;
}
identifyKilobot(currentID);
if (currentID <= maxIDtoCheck) qDebug() << "Try ID" << currentID;
}
}
this->drawOverlay(display);
this->showMat(display);
//this->showMat(this->finalImageCol);
}
void KilobotTracker::identifyKilobot(int id, bool runtime = false){
// decompose id
QVector < uint8_t > data(9);
data[0] = id >> 8;
data[1] = id & 0xFF;
kilobot_broadcast msg;
if (runtime) {
msg.type = 119;
} else {
msg.type = 120;
}
msg.data = data;
emit this->broadcastMessage(msg);
}
void KilobotTracker::identifyKilobot(int id)
{
// decompose id
QVector < uint8_t > data(9);
data[0] = id >> 8;
data[1] = id & 0xFF;
kilobot_broadcast msg;
msg.type = 120;
msg.data = data;
emit this->broadcastMessage(msg);
}
QString type2str(int type) {
QString r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;
}
void KilobotTracker::trackKilobots()
{
// convert for display
#ifdef USE_CUDA
Mat display;
Mat temp_for_reacquire;
this->finalImageB.download(temp_for_reacquire);
cv::cvtColor(temp_for_reacquire, display, CV_GRAY2RGB);
#else
Mat display;
cv::cvtColor(this->finalImage, display, CV_GRAY2RGB);
#endif
switch (this->trackType) {
{
case NO_TRACK:
this->showMat(display);
return;
}
{
case CIRCLES_NAIVE:
if (this->kilos.size() == 0) break;
int circle_acc = this->houghAcc;
cuda::GpuMat circlesGpu;
vector < cuda::GpuMat > circChans;
vector < cuda::GpuMat > kbChans;
this->hough->setVotesThreshold(circle_acc);
this->hough->detect(this->finalImageB,circlesGpu,stream);
//***************************************************************
// FOR DEGUB: draw all the circles found through GPU-hough
// vector<Vec3f> circles;
// circlesGpu.download(circles);
// for( size_t i = 0; i < circles.size(); i++ )
// {
// Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
// int radius = cvRound(circles[i][2]);
// // draw the circle outline
// circle( display, center, radius, Scalar(50,255,255), 1, 8, 0 );
// }
//***************************************************************
// get the channels so we can get rid of the sizes and use locations only
cuda::split(circlesGpu,circChans);
cuda::split(kbLocs,kbChans);
//#define DEBUG_TRACKING true
Mat xCpu;
Mat yCpu;
circChans[0].download(xCpu);
circChans[1].download(yCpu);
#ifdef DEBUG_TRACKING
Mat szCpu;