-
Notifications
You must be signed in to change notification settings - Fork 0
/
findtargets.cpp
2193 lines (1788 loc) · 62.3 KB
/
findtargets.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
// Targeter - target identification software for EUCALL workpackage 6
// Licensed under the GPL License. See LICENSE file in the project root for full license information.
// Copyright(C) 2017 David Watts
#include <iostream>
#include <iomanip>
#include <limits>
#include <QDebug>
#include <vector>
#include <QSharedPointer>
#include "opencv2/opencv.hpp"
#include "opencv/highgui.h"
#include "globals.h"
#include "HelperFunctions.h"
#include "imageprocessing.h"
#include "mainwindow.h"
#include "findtargets.h"
#include "Haar.h"
// cuda gpu functions
#ifdef _CUDA_CODE_COMPILE_
#include <opencv2/core/cuda.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudaimgproc.hpp>
#include "targetDetectionGPU.h"
#endif
using namespace cv;
typedef std::numeric_limits< float > dbl;
using namespace std;
template<typename T>
void FindTargets::printVector(const T& t) {
std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::qDebug, ", "));
}
// functions follow ////////////////////////////////////////////////////////////////
/**
*
* Prints to screen vector of cluster structures
*
* @author David Watts
* @since 2017/03/07
*
* FullName printClusterVector
* Qualifier
* @param std::vector<T> cluster
* @return void
* Access public
*/
template<typename T>
void FindTargets::printClusterVector(QVector<T> cluster)
{
QVector<T>::iterator iI;
int i = 0;
for (iI = cluster.begin(); iI != cluster.end(); iI++)
{
i++;
std::string s = "cluster";
(*iI).printMe(s + std::to_string(i));
}
}
/**
*
* Prints to screen values of Coocurance matrix
*
* @author David Watts
* @since 2017/03/07
*
* FullName printCoocuranceHistogram
* Qualifier
* @param T * hist
* @param int dim1
* @param int dim2
* @param int dim3
* @param int nDim3
* @return void
* Access public
*/
template<typename T>
void FindTargets::printCoocuranceHistogram(T* hist, int dim1, int dim2, int dim3, int nDim3)
{
int i, j, k, ind;
if (dim3 <= 0)
{
for (i = 0; i<dim2; i++)
{
for (j = 0; j<dim1; j++)
DBOUT(hist[i + j*dim1] << " ");
}
DBOUT(std::endl);
}
else
{
for (k = 0; k<dim3; k++)
{
DBOUT("d=" << k << endl);
for (j = 0; j<dim2; j++)
{
for (i = 0; i<dim1; i++)
{
//ind = i + dim2 * (j*dim1+k);
//(z * dim1 * dim2) + (y * dim1) + x;
ind = i + j*dim1 + k*dim1*dim2;
DBOUT(hist[ind] << "\t"); //i + height* (j + width* k)
}
DBOUT(std::endl);
}
DBOUT(std::endl);
}
DBOUT(std::endl);
}
}
// end of helper functions ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
*
* Detects target image (trainingImage) in detectionImage using Laplacian method
*
* @author David Watts
* @since 2017/04/25
*
* FullName LaplacianFindObject
* Qualifier
* @param std::vector<targeterImage> & trainingImages
* @param targeterImage & detectionImage
* @return cv::Mat
* Access public
*/
cv::Mat FindTargets::LaplacianFindObject(QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages, QExplicitlySharedDataPointer<targeterImage> detectionImage, int distance, int NoClusters)
{
cv::Mat im;
// padd target image to be multiple of 2^N - this is to be region size
int maxDim = 0;
for (int i = 0; i < trainingImages.size(); i++)
maxDim = MIN(maxDim, MAX(trainingImages[0]->Cols(), trainingImages[0]->Rows()));
int NextPow = round(pow(2, ceil(log2(maxDim))));
return im;
}
/*
Steerable filters wavelet or laplacian filter->N orientations at each freq,
joint pdf for each orientation pair -> n pdf's * frequency levels,
or difference in orientation,
detection is by cooc comparison.
Can also do shrinkage to make pdf sparse to a list can be used instead.
Can find shrinkage for target by increasing threshold and looking at reconstruction error function of threshold.
Then apply best threshold to entire transform.
*/
//************************************
// Method: FindTargetsHaar
// FullName: FindTargets::FindTargetsHaar
// Access: public
// Returns: bool
// Qualifier:
// Parameter: QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages
// Parameter: QExplicitlySharedDataPointer<targeterImage> detectionImage
// Parameter: int levels
//************************************
bool FindTargets::FindTargetsHaar(QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages,
QExplicitlySharedDataPointer<targeterImage> detectionImage, int levels)
{
// perform transform of target images
for(int i=0; i<trainingImages.size();i++)
{
cv::Mat im;
cv::cvtColor(trainingImages[i]->getImage(), im, CV_BGR2GRAY, 1);
im.convertTo(im, CV_64FC1);
double minVal = 0, maxVal = 0;
cv::minMaxLoc(im, &minVal, &maxVal);
Haar::Haar2(im, levels);
// shrinkage of target transforms by threshold -> store threshold
cv::Mat coocImage;
// collect statistics on target images - orientation vs magnitude cooc matrix
Haar::getHaarCooc(im, coocImage, im.cols, im.rows, levels, (float)maxVal);
return true;
}
// compare with regions of detect image
return true;
}
/**
*
* Finds template image (trainingImages) in detectionImage using OpenCV matchTemplate method
*
* @author David Watts
* @since 2017/03/07
*
* FullName CVMatching
* Qualifier
* @param std::vector<targeterImage> & trainingImages
* @param targeterImage & detectionImage
* @param algoType matchType
* @param MainWindow * pMainWindow
* @return void * Access public
*/
cv::Mat FindTargets::CVMatching(QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages, QExplicitlySharedDataPointer<targeterImage> detectionImage, algoType::algoType matchType, bool bCorrectBackground)
{
#ifdef DEBUGPRINT
DBOUT("Function Name: " << Q_FUNC_INFO << std::endl);
#endif
bool bExpandImageBoundaries = false;
/// Create the result matrix
int w = trainingImages[0]->Cols();
int h = trainingImages[0]->Rows();
cv::Size dstSize;
cv::Mat dst, dst_border;
dstSize = detectionImage->Size();
dst = detectionImage->getImage();
copyMakeBorder(dst, dst, h/2, h/2, w/2, w/2, BORDER_REPLICATE);
if (bCorrectBackground)
{
cv::Mat out;
ImageProcessing ip;
dst = ip.subtractBackground(dst, out);
}
int dw = dst.cols;
int dh = dst.rows;
cv::Mat detect = trainingImages[0]->getImage();
cv::Mat result((dw - w + 1), (dh - h + 1), CV_32FC1);
DBOUT("dst type " << HelperFunctions::type2str(dst.type()).toLocal8Bit().data());
DBOUT("detect type " << HelperFunctions::type2str(detect.type()).toLocal8Bit().data());
/// Do the Matching and Normalize
cv::matchTemplate(dst, detect, result, matchType);
cv::Mat sim = HelperFunctions::convertFloatToGreyscaleMat(result);
cv::Mat fullSizeImage(dstSize.height, dstSize.width, dst.type());
sim.copyTo(fullSizeImage(cv::Rect(w/2, h/2, sim.cols, sim.rows)));
return fullSizeImage;
}
////////////////////////////// laws method /////////////////////////////////////////////////////////
//************************************
// Method: sepConvolve
// FullName: FindTargets::sepConvolve
// Access: public
// Returns: void
// Qualifier:
// Parameter: const cv::Mat spImage
// Parameter: cv::Mat & spResult
// Parameter: const float Kernel[]
// Parameter: int KernelLen
// Parameter: bool bRow
//************************************
void FindTargets::sepConvolve(const cv::Mat spImage, cv::Mat& spResult, const float Kernel[/* KernelLen */], int KernelLen, bool bRow)
{
int r= spImage.rows, c= spImage.cols;
if(bRow)
{
for (int j = 0; j < r; j++)
{
for (int i = 0; i < c; i++)
{
spResult.at<float>(j, i) = 0;
for (int k = 0; k < KernelLen; k++)
{
int ind = i - k;
//mirror
if (ind > c - 1)
ind = c - (ind - c);
else if (ind < 0)
ind = -ind;
spResult.at<float>(j, i) = spResult.at<float>(j, i) + spImage.at<float>(j, ind) * Kernel[k]; // convolve: multiply and accumulate
}
}
}
}
else
{
for (int i = 0; i < c; i++)
{
for (int j = 0; j < r; j++)
{
spResult.at<float>(j, i) = 0;
for (int k = 0; k < KernelLen; k++)
{
int ind = j - k;
//mirror
if (ind > r - 1)
ind = r - (ind - r);
else if (ind < 0)
ind = -ind;
spResult.at<float>(j, i) = spResult.at<float>(j, i) + spImage.at<float>(ind, i) * Kernel[k]; // convolve: multiply and accumulate
}
}
}
}
}
//************************************
// Method: addHistogram
// FullName: FindTargets::addHistogram
// Access: public
// Returns: void
// Qualifier:
// Parameter: cv::Mat & hist
// Parameter: cv::Mat aim
// Parameter: cv::Mat bim
// Parameter: cv::Mat cim
// Parameter: cv::Mat dim
// Parameter: int noBins
// Parameter: int histrange
// Parameter: bool append
//************************************
void FindTargets::addHistogram(cv::Mat& hist, cv::Mat aim, cv::Mat bim, cv::Mat cim, cv::Mat dim, int noBins, int histrange, bool append)
{
float range[] = { -histrange, histrange };
const float* histRange = { range };
bool uniform = true;
if(!aim.empty())
getHistogram(aim, hist, noBins, histrange, append);
if(!bim.empty())
getHistogram(bim, hist, noBins, histrange, true);
if(!cim.empty())
getHistogram(cim, hist, noBins, histrange, true);
if(!dim.empty())
getHistogram(dim, hist, noBins, histrange, true);
hist.at<float>(noBins>>1, 0) = 0;
}
void FindTargets::getHistogram(cv::Mat input, cv::Mat& histogram, int noBins, int histrange, bool append)
{
// cuda histogram on deals with uchar/short types!
/*
#ifdef _CUDA_CODE_COMPILE_
cv::cuda::GpuMat hist(1, noBins, CV_32S);
cv::cuda::GpuMat inImage;
inImage.upload(input);
cv::cuda::histEven(inImage, hist, noBins, -histrange, histrange);
cv::Mat result_host;
hist.download(histogram);
#else
*/
float range[] = { -histrange, histrange };
const float* histRange = { range };
cv::calcHist(&input, 1, 0, cv::Mat(), histogram, 1, &noBins, &histRange, true, append);
/*
#endif
*/
}
//************************************
// Method: scoreLawsHistogram
// FullName: FindTargets::scoreLawsHistogram
// Access: public
// Returns: double
// Qualifier:
// Parameter: QVector<cv::Mat> lawsMapDetect
// Parameter: QVector<cv::Mat> lawsHistTarget
// Parameter: QVector<float> biases
//************************************
double FindTargets::scoreLawsHistogram(QVector<cv::Mat> lawsMapDetect, QVector<cv::Mat> lawsHistTarget, QVector<float> biases)
{
float score = 0;
for (int i = 0; i < lawsHistTarget.length(); i++)
{
float bias = 1.0/float(lawsHistTarget.length());
if (biases.length() >= i && biases[i] >= 0 && biases[i] <= 1)
bias = biases[i];
// should bias the histogram with the strongest response in the test images
score += compareHist(lawsHistTarget[i], lawsMapDetect[i], cv::HISTCMP_CHISQR) * bias;
}
return score;
}
//************************************
// Method: getLawFilteredImages
// FullName: FindTargets::getLawFilteredImages
// Access: public
// Returns: QT_NAMESPACE::QMap<QT_NAMESPACE::QString, cv::Mat>
// Qualifier:
// Parameter: cv::Mat im
//************************************
QMap<QString, cv::Mat> FindTargets::getLawFilteredImages(cv::Mat im)
{
QMap<QString, cv::Mat> lawsMapTarget;
float L[5] = { 1, 4, 6, 4, 1 };
float E[5] = { -1, -2, 0, 2, 1 };
float ER[5] = { 1, 2, 0, -2, -1 };
float S[5] = { -1, 0, 2, 0, -1 };
float R[5] = { 1, -4, 6, -4, 1 };
//float W5[5] = { -1, 2, 0, -2, 1};
int r = im.rows, c = im.cols, t = im.type();
cv::Mat tempIm = cv::Mat(r, c, t);
// first 1D filter on X
sepConvolve(im, tempIm, L, 5, true);
cv::Mat temp1 = tempIm.clone();
lawsMapTarget["im_L"] = temp1;
sepConvolve(im, tempIm, E, 5, true);
lawsMapTarget["im_E"] = tempIm.clone();
sepConvolve(im, tempIm, ER, 5, true);
lawsMapTarget["im_ER"] = tempIm.clone();
sepConvolve(im, tempIm, S, 5, true);
lawsMapTarget["im_S"] = tempIm.clone();
sepConvolve(im, tempIm, R, 5, true);
lawsMapTarget["im_R"] = tempIm.clone();
// other filtered images filtered in Y
// filtered images
// completely symmetric
sepConvolve(lawsMapTarget["im_S"], tempIm, S, 5, false);
lawsMapTarget["im_SS"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_R"], tempIm, R, 5, false);
lawsMapTarget["im_RR"] = tempIm.clone();
// 180 degree rotationally symmetric
//cv::Mat LSSL = (sepConvolve(im_L, S, 5, false) + sepConvolve(im_S, L, 5, false)) / 2.0;
sepConvolve(lawsMapTarget["im_L"], tempIm, S, 5, false);
lawsMapTarget["im_LS"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_S"], tempIm, L, 5, false);
lawsMapTarget["im_SL"] = tempIm.clone();
//cv::Mat SRRS = (sepConvolve(im_S, R, 5, false) + sepConvolve(im_R, S, 5, false)) / 2.0;
sepConvolve(lawsMapTarget["im_S"], tempIm, R, 5, false);
lawsMapTarget["im_SR"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_R"], tempIm, S, 5, false);
lawsMapTarget["im_RS"] = tempIm.clone();
//cv::Mat LRRL = (sepConvolve(im_L, R, 5, false) + sepConvolve(im_R, L, 5, false)) / 2.0;
sepConvolve(lawsMapTarget["im_E"], tempIm, E, 5, false);
lawsMapTarget["im_EE"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_E"], tempIm, ER, 5, false);
lawsMapTarget["im_EER"] = tempIm.clone();
// 90 Degree rotationally symmetric - Anything with E and another type of filter!
// either average like below or add to same histogram for filter type
/*
//cv::Mat LEEL = (sepConvolve(im_L, E, 5, false) + sepConvolve(im_E, L, 5, false)) / 2.0;
cv::Mat EL_LE_LER_ERL = (sepConvolve(im_E, L, 5, false) +
sepConvolve(im_L, E, 5, false) +
sepConvolve(im_L, ER, 5, false) +
sepConvolve(im_ER, L, 5, false)) / 4.0;
*/
sepConvolve(lawsMapTarget["im_E"], tempIm, L, 5, false);
lawsMapTarget["im_EL"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_L"], tempIm, E, 5, false);
lawsMapTarget["im_LE"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_L"], tempIm, ER, 5, false);
lawsMapTarget["im_LER"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_ER"], tempIm, L, 5, false);
lawsMapTarget["im_ERL"] = tempIm.clone();
/*
//cv::Mat ESSE = (sepConvolve(im_E, S, 5, false) + sepConvolve(im_S, E, 5, false)) / 2.0;
cv::Mat ES_SE_SER_ERS = (sepConvolve(im_E, S, 5, false) +
sepConvolve(im_S, E, 5, false) +
sepConvolve(im_S, ER, 5, false) +
sepConvolve(im_ER, S, 5, false)) / 4.0;
*/
sepConvolve(lawsMapTarget["im_E"], tempIm, S, 5, false);
lawsMapTarget["im_ES"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_S"], tempIm, E, 5, false);
lawsMapTarget["im_SE"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_S"], tempIm, ER, 5, false);
lawsMapTarget["im_SER"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_ER"], tempIm, S, 5, false);
lawsMapTarget["im_ERS"] = tempIm.clone();
/*
//cv::Mat ERRE = (sepConvolve(im_E, R, 5, false) + sepConvolve(im_R, E, 5, false)) / 2.0;
cv::Mat ER_RE_RER_ERR = (sepConvolve(im_E, R, 5, false) +
sepConvolve(im_R, E, 5, false) +
sepConvolve(im_R, ER, 5, false) +
sepConvolve(im_ER, R, 5, false)) / 4.0;
*/
sepConvolve(lawsMapTarget["im_E"], tempIm, R, 5, false);
lawsMapTarget["im_ER"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_R"], tempIm, E, 5, false);
lawsMapTarget["im_RE"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_R"], tempIm, ER, 5, false);
lawsMapTarget["im_RER"] = tempIm.clone();
sepConvolve(lawsMapTarget["im_ER"], tempIm, R, 5, false);
lawsMapTarget["im_ERR"] = tempIm.clone();
return lawsMapTarget;
}
//************************************
// Method: getLawFilterHistograms
// FullName: FindTargets::getLawFilterHistograms
// Access: public
// Returns: void
// Qualifier:
// Parameter: cv::Mat im
// Parameter: QVector<cv::Mat> & lawsHistTarget
// Parameter: int histSize
// Parameter: int histRange
// Parameter: bool bAccumulateHistograms
//************************************
void FindTargets::getLawFilterHistograms(cv::Mat im, QVector<cv::Mat>& lawsHistTarget, int histSize, int histRange, bool bAccumulateHistograms)
{
cv::cvtColor(im, im, CV_BGR2GRAY, 1);
im.convertTo(im, CV_32FC1);
QMap<QString, cv::Mat> lawsMapTarget = getLawFilteredImages(im);
if(bAccumulateHistograms == false || lawsHistTarget.length() == 0 )
{
for (int c = 0; c < 8; c++)
lawsHistTarget.append(cv::Mat());
}
getLawFilterHistograms(lawsHistTarget, lawsMapTarget, cv::Rect(), histSize, histRange, bAccumulateHistograms);
}
void FindTargets::getLawFilterHistograms(QVector<cv::Mat>& lawsHist, QMap<QString, cv::Mat> lawsMap, cv::Rect roi, int histSize, int histRange, bool bAccumulateHistograms)
{
if(roi.x >= 0 && roi.y >= 0 && roi.width > 0 && roi.height > 0)
{
addHistogram(lawsHist[0], lawsMap["im_SS"](roi), cv::Mat(), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[1], lawsMap["im_RR"](roi), cv::Mat(), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[2], lawsMap["im_LS"](roi), lawsMap["im_SL"](roi), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[3], lawsMap["im_SR"](roi), lawsMap["im_RS"](roi), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[4], lawsMap["im_EE"](roi), lawsMap["im_EER"](roi), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[5], lawsMap["im_EL"](roi), lawsMap["im_LE"](roi), lawsMap["im_LER"](roi), lawsMap["im_ERL"](roi), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[6], lawsMap["im_ES"](roi), lawsMap["im_SE"](roi), lawsMap["im_SER"](roi), lawsMap["im_ERS"](roi), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[7], lawsMap["im_ER"](roi), lawsMap["im_RE"](roi), lawsMap["im_RER"](roi), lawsMap["im_ERR"](roi), histSize, histRange, bAccumulateHistograms);
}
else
{
addHistogram(lawsHist[0], lawsMap["im_SS"], cv::Mat(), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[1], lawsMap["im_RR"], cv::Mat(), cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[2], lawsMap["im_LS"], lawsMap["im_SL"], cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[3], lawsMap["im_SR"], lawsMap["im_RS"], cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[4], lawsMap["im_EE"], lawsMap["im_EER"], cv::Mat(), cv::Mat(), histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[5], lawsMap["im_EL"], lawsMap["im_LE"], lawsMap["im_LER"], lawsMap["im_ERL"], histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[6], lawsMap["im_ES"], lawsMap["im_SE"], lawsMap["im_SER"], lawsMap["im_ERS"], histSize, histRange, bAccumulateHistograms);
addHistogram(lawsHist[7], lawsMap["im_ER"], lawsMap["im_RE"], lawsMap["im_RER"], lawsMap["im_ERR"], histSize, histRange, bAccumulateHistograms);
}
}
//************************************
// Method: getHistogramWeights
// FullName: FindTargets::getHistogramWeights
// Access: public
// Returns: void
// Qualifier:
// Parameter: QVector<cv::Mat> hists
// Parameter: QVector<float> & biases
//************************************
void FindTargets::getHistogramWeights(QVector<cv::Mat> hists, QVector<float>& biases)
{
biases = QVector<float>(hists.length());
double bsum = 0;
// get sum of histogram to use in an importance measure
for (int i = 0; i < hists.length(); i++)
{
biases[i] = cv::sum(hists[i])[0]; // or entropy?
bsum += biases[i];
}
//normalise
for (int i = 0; i < hists.length(); i++)
biases[i] /= bsum;
}
//************************************
// Method: detectLawsTextureFeatures
// FullName: FindTargets::detectLawsTextureFeatures
// Access: public
// Returns: cv::Mat
// Qualifier:
// Parameter: cv::Mat detectionImage
// Parameter: QVector<cv::Mat> lawsHistTarget
// Parameter: QVector<float> biases
//************************************
cv::Mat FindTargets::detectLawsTextureFeatures(cv::Mat detectionImage, QVector<cv::Mat> lawsHistTarget, QVector<float> biases, bool bCorrectBackground)
{
#ifdef _CUDA_CODE_COMPILE_
int inc = 1;
#else
int inc = 10;
#endif
int regionSize = 15;
int histRange = 128;
int histSize = 10;
// now get detection
cv::Mat im, scoreImage(detectionImage.rows, detectionImage.cols, CV_32FC1);
// now filter detect image and compare histograms of regions of the image
cv::cvtColor(detectionImage, im, CV_BGR2GRAY, 1);
if (bCorrectBackground)
{
cv::Mat out;
ImageProcessing ip;
im = ip.subtractBackground(im, out);
}
im.convertTo(im, CV_32FC1);
QMap<QString, cv::Mat> lawsMapDetect = getLawFilteredImages(im);
QVector<cv::Mat> lawsHistDetect;
for (int c = 0; c < 8; c++)
lawsHistDetect.append(cv::Mat());
// but this has to be on regions of the detection image
for (int i = 0; i < im.cols; i += inc)
for (int j = 0; j < im.rows; j += inc)
{
int regionSizeI = regionSize;
int regionSizeJ = regionSize;
if (i + regionSize >= im.cols)
regionSizeI = im.cols - i;
if (j + regionSize >= im.rows)
regionSizeJ = im.rows - j;
// get histograms in this region of the image
cv::Rect roi(i, j, regionSizeI, regionSizeJ);
getLawFilterHistograms(lawsHistDetect, lawsMapDetect, roi, histSize, histRange, false);
//score detect region using target histogram
float s = scoreLawsHistogram(lawsHistDetect, lawsHistTarget, biases);
for (int k = i; k < i + inc; k++)
for (int l = j; l < j + inc; l++)
scoreImage.at<float>(l, k) = s;
}
// create greyscale image of score
cv::Mat sim = HelperFunctions::convertFloatToGreyscaleMat(scoreImage);
return sim;
}
//************************************
// Method: lawsTextureFeatures
// FullName: FindTargets::lawsTextureFeatures
// Access: public
// Returns: cv::Mat
// Qualifier:
// Parameter: QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages
// Parameter: QExplicitlySharedDataPointer<targeterImage> detectionImage
//************************************
cv::Mat FindTargets::lawsTextureFeatures(QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages,
QExplicitlySharedDataPointer<targeterImage> detectionImage, bool bCorrectBackground)
{
int histRange = 128;
int histSize = 10;
QVector<cv::Mat> lawsHistTarget;
for (int i = 0, hs = 0; i < trainingImages.size(); i++)
getLawFilterHistograms(trainingImages[i]->getImage(), lawsHistTarget, histSize, histRange, true);
//return HelperFunctions::displayHistogram(lawsHistTarget[7], histSize);
// get vector of filter weights
QVector<float> biases;
getHistogramWeights(lawsHistTarget, biases);
return detectLawsTextureFeatures(detectionImage->getImage(), lawsHistTarget, biases, bCorrectBackground);
}
void FindTargets::trainLawsTextureFeatures(QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages, QVector<cv::Mat>& lawsHistTarget, QVector<float>& lawsHistBiases)
{
int histRange = 128;
int histSize = 10;
lawsHistTarget.clear();
for (int i = 0, hs = 0; i < trainingImages.size(); i++)
getLawFilterHistograms(trainingImages[i]->getImage(), lawsHistTarget, histSize, histRange, true);
//return HelperFunctions::displayHistogram(lawsHistTarget[7], histSize);
// get vector of filter weights
getHistogramWeights(lawsHistTarget, lawsHistBiases);
}
cv::Mat FindTargets::HaarHistogram(QVector<QExplicitlySharedDataPointer<targeterImage>> trainingImages, QExplicitlySharedDataPointer<targeterImage> detectionImage, int distance, int NoClusters, bool bProcessGrayscale)
{
cv::Mat sim = cv::Mat();
return sim;
}
/////////////////////////// cooc target detection ////////////////////////////////////////////////////////////////
void FindTargets::trainColourOccuranceHistogram(QVector<QExplicitlySharedDataPointer<targeterImage>>& trainingImages,
QExplicitlySharedDataPointer<targeterImage>& detectionImage, COOCMatrix* coocTraining,
int regionDistance, int distanceBins, int NoClusters, bool bCrossEntropy,
bool bProcessGrayscale, bool bFASTCOOC)
{
#ifdef DEBUGPRINT
DBOUT("Function Name: " << Q_FUNC_INFO << std::endl);
#endif
// training phase ////
if(trainingImages.length()<=0)
return;
int histSizeIntensity = 256;
int histSizeHue = 180;
int* clusterHistIntensity = new int[histSizeIntensity];
int* clusterHistHue = new int[histSizeHue];
int* clusterImageIntensity = nullptr;
int* clusterImageHue = nullptr;
// should be taken out of here and produced when the target image is created
// cluster intensity and hue of images
bool isColour = HelperFunctions::isGrayImage(detectionImage->getImage());
int maxw = trainingImages[0]->Rows();
int maxh = trainingImages[0]->Cols();
for (int i = 0; i < trainingImages.length(); i++)
{
maxw = MAX(maxw, trainingImages[i]->Cols());
maxh = MAX(maxh, trainingImages[i]->Rows());
}
initialiseCOOCMatrix(coocTraining, maxw, maxh, regionDistance, distanceBins, NoClusters, bFASTCOOC);
for(int i=0; i<trainingImages.length(); i++)
{
int w = trainingImages[i]->Cols();
int h = trainingImages[i]->Rows();
clusterImageIntensity = new int[w*h];
clusterImageHue = new int[w*h];
HistogramClustering(trainingImages[i]->getImage(), coocTraining, clusterImageIntensity, clusterImageHue,
histSizeIntensity, histSizeHue, NoClusters, bProcessGrayscale, isColour);
// generate concurrence matrices from training images
getCoocuranceHistogram(clusterImageIntensity, clusterImageHue, trainingImages[i]->get1DImage(imageType::mask), trainingImages[i]->getMaskType(),
w, h, coocTraining, bProcessGrayscale, HelperFunctions::isGrayImage(trainingImages[i]->getImage()), bFASTCOOC);
if (clusterImageIntensity != nullptr)
delete[] clusterImageIntensity;
if (clusterImageHue != nullptr)
delete[] clusterImageHue;
}
if (clusterHistIntensity != nullptr)
delete[] clusterHistIntensity;
if (clusterHistHue != nullptr)
delete[] clusterHistHue;
}
/**
*
* Uses histogram cluster merging method to posterise grayscale image into NoCluster number of levels
*
* @author David Watts
* @since 2017/03/07
*
* FullName HistogramClusteringGray
* Qualifier
* @param targeterImage & detectionImage
* @param std::vector<targeterImage> & TrainImages
* @param int NoClusters
* @param MainWindow * pMainWindow
* @return void
* Access public
*/
void FindTargets::HistogramClustering(cv::Mat im, COOCMatrix* cooc, int* clusterImageIntensity, int* clusterImageHue,
int histSizeIntensity, int histSizeHue, int NoClusters, bool bProcessGrayscale, bool imageIsGray)
{
std::vector<cv::Mat> hsv_planes;
cv::Mat image1_gray;
cv::Scalar mean, stdev;
if (imageIsGray)
{
DBOUT("greyscale image" << std::endl);
if (bProcessGrayscale)
{
cv::cvtColor(im, image1_gray, CV_BGR2GRAY);
cooc->averageIntensity = HistogramClusterImage(cooc->intensityHist, &image1_gray, clusterImageIntensity, histSizeIntensity, NoClusters);
}
else
{
split(im, hsv_planes);
#ifdef DEBUGIMAGES
imshow("gray", hsv_planes[0]); // Show our image inside it.
#endif
cooc->averageIntensity = HistogramClusterImage(cooc->intensityHist, &hsv_planes[1], clusterImageIntensity, histSizeIntensity, NoClusters);
}
}
else
{
cv::Mat hsvImage;
std::vector<cv::Mat> hsv_planes;
DBOUT("colour image" << std::endl);
cv::cvtColor(im, hsvImage, CV_BGR2HLS);
split(hsvImage, hsv_planes);
#ifdef DEBUGIMAGES
cv::String s = "hue ";
namedWindow(s, WINDOW_AUTOSIZE);// Create a window for display.
imshow(s, hsv_planes[0]); // Show our image inside it.
#endif
cooc->averageIntensity = HistogramClusterImage(cooc->intensityHist, &hsv_planes[1], clusterImageIntensity, histSizeIntensity, NoClusters);
cooc->averageHue = HistogramClusterImage(cooc->hueHist, &hsv_planes[0], clusterImageHue, histSizeHue, NoClusters);
}
}
/**
*
* Detects target image (trainingImage) in detectionImage using colour coocurrance matrix matching method
*
* @author David Watts
* @since 2017/03/07
*
* FullName ColourOccuranceHistogram
* Qualifier
* @param std::vector<targeterImage> & trainingImages
* @param targeterImage & detectionImage
* @param int distance
* @param int NoClusters
* @param MainWindow * pMainWindow
* @return void
* Access public
*/
cv::Mat FindTargets::ColourOccuranceHistogram(QVector<QExplicitlySharedDataPointer<targeterImage>>& trainingImages,
QExplicitlySharedDataPointer<targeterImage>& detectionImage,
COOCMatrix* coocTraining, int regionDistance, int distanceBins,
int NoClusters, bool bCrossEntropy, bool bProcessGrayscale, bool bFASTCOOC,
bool bCorrectBackground)
{
#ifdef DEBUGPRINT
DBOUT("Function Name: " << Q_FUNC_INFO << std::endl);
#endif
// training phase ////
trainColourOccuranceHistogram(trainingImages, detectionImage, coocTraining, regionDistance, distanceBins, NoClusters,
bCrossEntropy, bProcessGrayscale, bFASTCOOC);
// cluster detect image
// testing phase
cv::Mat score = detectCOOCHistogram(detectionImage->getImage(), coocTraining, bCrossEntropy, bProcessGrayscale, bFASTCOOC, bCorrectBackground);
// clean up
if (coocTraining->coMatrixHue != nullptr)
delete[] coocTraining->coMatrixHue;
if (coocTraining->coMatrixIntensity != nullptr)
delete[] coocTraining->coMatrixIntensity;
return score;
}
void FindTargets::initialiseCOOCMatrix(COOCMatrix* cooc, int w, int h, int regionDistance, int distanceBins, int NoClusters, bool bFASTCOOC)
{
int regionWidth = w;
int regionHeight = h;
bool bSuccess = true;
#ifdef _CUDA_CODE_COMPILE_
// limit it to warp size
regionDistance = MIN(32, regionDistance);
int optiDist = 16;
#endif
// limit it to maximum size of region
regionWidth = MIN(regionDistance, regionWidth);
regionHeight = MIN(regionDistance, regionHeight);
#ifdef _CUDA_CODE_COMPILE_
int inc_W = 1;
int inc_H = 1;
#else
if(bFASTCOOC)
{
int inc_W = 1;
int inc_H = 1;
}
else
{
int inc_W = regionWidth / 2;
int inc_H = regionHeight / 2;
}
#endif
// distance should not be more than 32 as should sizes for CUDA
regionDistance = MAX(regionWidth, regionHeight);
// make distance divisible by 2
//distance = (distance >> 1) << 1;
int rw = regionWidth - 1;
int rh = regionHeight - 1;
float maxDist = ceil(sqrt(rw*rw + rh*rh));
// clusters test and training images for RGB values
cooc->coMatrixHue = nullptr;
cooc->coMatrixIntensity = nullptr;
if(bFASTCOOC)
{
cooc->coDIMX = NoClusters*2;
cooc->coDIMY = distanceBins;
}
else
{
cooc->coDIMX = NoClusters;
cooc->coDIMY = NoClusters;
}
cooc->coDIMZ = distanceBins;
cooc->regionHeight = regionHeight;
cooc->regionWidth = regionWidth;
cooc->maxDist = maxDist;
cooc->incrementWidth = inc_W;
cooc->incrementHeight = inc_H;
int CoocSize = cooc->coDIMX*cooc->coDIMY*cooc->coDIMZ;