-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageprocessing.cpp
1845 lines (1458 loc) · 42.6 KB
/
imageprocessing.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 "opencv2/opencv.hpp"
#include "opencv/highgui.h"
#include <zbar64/include/zbar.h>
#include "imageprocessing.h"
#include "HelperFunctions.h"
#include "globals.h"
using namespace cv;
using namespace std;
using namespace zbar;
QString ImageProcessing::scanForBarCodes(const cv::Mat& src, cv::Mat& dst, bool displayOK)
{
QString tag;
//scanner setup
ImageScanner scanner;
scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);
int width = src.cols;
int height = src.rows;
/// Detector parameters
uchar* raw = nullptr;
cv::Mat gray = Mat::zeros(src.size(), CV_8UC1);
dst = src.clone();
if(src.channels() != 1)
{
cvtColor(src, gray, CV_BGR2GRAY);
// wrap image data
raw = (uchar *)gray.data;
}
else
raw = (uchar *)src.data;
Image image(width, height, "Y800", raw, width * height);
// scan the image for barcodes
scanner.scan(image);
std::string TAG;
// extract results
for (Image::SymbolIterator symbol = image.symbol_begin(); symbol != image.symbol_end(); ++symbol)
{
TAG = symbol->get_data();
if (TAG.size() != 14)
continue;
//print tag
tag = QString(TAG.c_str());
//define vector of points
vector<Point> vp;
if (displayOK)
{
int n = symbol->get_location_size();
//get bar code location in image
for (int i = 0; i < n; i++)
{
vp.push_back(Point(symbol->get_location_x(i), symbol->get_location_y(i)));
}
//build rectangle around the bar code
RotatedRect r = minAreaRect(vp);
Point2f pts[4];
r.points(pts);
//draw lines
for (int i = 0; i < 4; i++)
{
line(dst, pts[i], pts[(i + 1) % 4], Scalar(255, 0, 0), 3);
}
}
}
return tag;
}
/*
void ImageProcessing::polyfit(const Mat& src_x, const Mat& src_y, Mat& dst, int order)
{
CV_Assert((src_x.rows > 0) && (src_y.rows > 0) && (src_x.cols == 1) && (src_y.cols == 1) && (dst.cols == 1) && (dst.rows == (order + 1)) && (order >= 1));
Mat copy, X_t, X_inv, temp2;
Mat X = Mat::zeros(src_x.rows, order + 1, CV_32FC1);
for (int i = 0; i <= order; i++)
{
copy = src_x.clone();
pow(copy, i, copy); // create vector of i^order
Mat M1 = X.col(i); // get reference of column i of Mat X
copy.col(0).copyTo(M1); // copy power values to x(i)
}
transpose(X, X_t); // transpose matrix
Mat temp = X_t * X; // multiply transpose by itself
invert(temp, temp2); // invert and solve matrix
Mat temp3 = temp2 * X_t; // multiply result by the transpose
Mat W = temp3 * src_y; // multiply result by
W.copyTo(dst);
}
*/
int* ImageProcessing::fitPolynomial(int* ydata, int size, int max_orders)
{
int* newy = new int[size];
Mat M = Mat_<double>(size, max_orders);
Mat I = Mat_<double>(size, 1);
for (int i = 0; i < size; i++)
{
double y = double(i - size / 2) / double(size);
for (int order = 0; order < max_orders; order++)
{
double powy = pow(y, max_orders - order - 1);
M.at<double>(i, order) = powy;
}
I.at<double>(i, 0) = (double)ydata[i];
}
SVD s(M);
Mat q;
// fit background
s.backSubst(I, q);
for (int i = 0; i < size; i++)
{
double y = double(i - size / 2) / double(size);
double quad = 0;
for (int order = 0; order<max_orders; order++)
{
double powy = pow(y, max_orders - order - 1);
double qt = q.at<double>(order, 0);
quad += qt * powy;
}
newy[i] = quad;
}
return newy;
}
cv::Mat ImageProcessing::subtractBackgroundChannel(cv::Mat inputImagePlane, cv::Mat& backgroundImagePlane)
{
if(inputImagePlane.channels()>1)
return cv::Mat();
cv::Mat bim = fitBackgroundImage(inputImagePlane);
cv::Mat gray_16S, dst_16S, bim_16S, dst;
inputImagePlane.convertTo(gray_16S, CV_16SC1);
bim.convertTo(bim_16S, CV_16SC1);
cv::subtract(gray_16S, bim_16S, dst_16S);
dst_16S = dst_16S + mean(bim_16S);
dst_16S.convertTo(dst, CV_8UC1);
bim_16S.convertTo(bim, CV_8UC1);
backgroundImagePlane = bim;
return dst;
}
cv::Mat ImageProcessing::subtractBackground(cv::Mat inputImage, cv::Mat& backgroundImage)
{
cv::Mat dst;
if (backgroundImage.empty())
backgroundImage = cv::Mat(inputImage.rows, inputImage.cols, inputImage.type());
if(inputImage.channels()==1)
{
dst = subtractBackgroundChannel(inputImage, backgroundImage);
}
else
{
std::vector<cv::Mat> rgb_planes;
std::vector<cv::Mat> rgb_background;
split(inputImage, rgb_planes);
split(backgroundImage, rgb_background);
rgb_planes[0] = subtractBackgroundChannel(rgb_planes[0], rgb_background[0]);
rgb_planes[1] = subtractBackgroundChannel(rgb_planes[1], rgb_background[1]);
rgb_planes[2] = subtractBackgroundChannel(rgb_planes[2], rgb_background[2]);
cv::merge(rgb_planes, dst);
cv::merge(rgb_background, backgroundImage);
}
return dst;
}
cv::Mat ImageProcessing::fitBackgroundImage(cv::Mat im)
{
Mat M = Mat_<double>(im.rows * im.cols, 6);
Mat I = Mat_<double>(im.rows * im.cols, 1);
for (int i = 0; i < im.rows; i++)
{
for (int j = 0; j < im.cols; j++)
{
double x = (j - im.cols / 2) / double(im.cols);
double y = (i - im.rows / 2) / double(im.rows);
M.at<double>(i*im.cols + j, 0) = x*x;
M.at<double>(i*im.cols + j, 1) = y*y;
M.at<double>(i*im.cols + j, 2) = x*y;
M.at<double>(i*im.cols + j, 3) = x;
M.at<double>(i*im.cols + j, 4) = y;
M.at<double>(i*im.cols + j, 5) = 1;
I.at<double>(i*im.cols + j, 0) = im.at<uchar>(i, j);
}
}
SVD s(M);
Mat q;
// fit background
s.backSubst(I, q);
cout << q;
cout << q.at<double>(2, 0);
Mat background(im.rows, im.cols, CV_8UC1);
for (int i = 0; i < im.rows; i++)
{
for (int j = 0; j < im.cols; j++)
{
double x = (j - im.cols / 2) / double(im.cols);
double y = (i - im.rows / 2) / double(im.rows);
double quad = q.at<double>(0, 0)*x*x +
q.at<double>(1, 0)*y*y +
q.at<double>(2, 0)*x*y +
q.at<double>(3, 0)*x +
q.at<double>(4, 0)*y +
q.at<double>(5, 0);
background.at<uchar>(i, j) = saturate_cast<uchar>(quad);
}
}
return background;
}
int* ImageProcessing::getRunLengthHistogram(cv::Mat& src, int& size, bool barLeftToRightBottomToTop)
{
QString tag = "";
int width = src.cols;
int height = src.rows;
/// Detector parameters
cv::Mat gray = Mat::zeros(src.size(), CV_8UC1);
if (src.channels() != 1)
cvtColor(src, gray, CV_BGR2GRAY);
else
gray = src;
double* hist = nullptr;
if (src.cols > src.rows)
{
size = gray.cols;
hist = new double[size];
if (barLeftToRightBottomToTop)
{
// accumulate in columns
for (int i = 0; i < size; i++)
{
hist[i] = 0;
for (int j = 0; j < gray.rows; j++)
{
unsigned char g = gray.ptr<uchar>(j)[i];
hist[i] += double(g) / double(gray.rows);
}
}
}
else
{
for (int i = size - 1; i >= 0; i--)
{
hist[i] = 0;
for (int j = 0; j < gray.rows; j++)
{
unsigned char g = gray.ptr<uchar>(j)[i];
hist[i] += double(g) / double(gray.rows);
}
}
}
}
else
{
size = gray.rows;
hist = new double[size];
if (barLeftToRightBottomToTop)
{
// accumulate in rows
for (int j = size - 1; j >= 0; j--)
{
hist[j] = 0;
for (int i = 0; i < gray.cols; i++)
{
unsigned char g = gray.ptr<uchar>(j)[i];
hist[j] += double(g) / double(gray.cols);
}
}
}
else
{
// accumulate in rows
for (int j = 0; j < size; j++)
{
hist[j] = 0;
for (int i = 0; i < gray.cols; i++)
{
unsigned char g = gray.ptr<uchar>(j)[i];
hist[j] += double(g) / double(gray.cols);
}
}
}
}
// copy over
int* ihist = new int[size];
for (int i = 0; i < size; i++)
ihist[i] = (int)hist[i];
delete [] hist;
return ihist;
}
int* ImageProcessing::thresholdOnMinimum(int* hist, int size, bool bAutoThreshold, int thresholdValue)
{
int* minimumValues = new int[size];
// find moving minimum
int windowSize = 31;
int win = windowSize >> 1;
int maxVal = 0;
// get minimum lines
for (int i = 0; i < size; i++)
{
int av = 0;
int ct = 0;
minimumValues[i] = MAXINT;
maxVal = MAX(hist[i], maxVal);
for (int j = i - win; j < i + win; j++)
{
if (j >= 0 && j < size)
minimumValues[i] = MIN(minimumValues[i], hist[j]);
}
}
// get stdev & mean
double sum = 0;
// get mean
for (int i = 0; i < size; i++)
sum += minimumValues[i];
sum /= size;
double stdev = 0;
for (int i = 0; i < size; i++)
stdev += pow((minimumValues[i] - sum), 2.0);
stdev /= size;
stdev = sqrt(stdev);
double threshold;
if(bAutoThreshold)
{
threshold = sum + 4.0*stdev;
}
else
{
threshold = (thresholdValue/100.0)*maxVal;
}
for (int i = 0; i < size; i++)
{
minimumValues[i] = threshold;
/*
if (hist[i] < threshold)
minimumValues[i] = 0;
else
minimumValues[i] = 1;
*/
}
// fit simple poly to values
return minimumValues;
}
int* ImageProcessing::movingAverageVector(int* hist, int size)
{
int* average = new int[size];
for (int i = 0; i < size-10; i+=10)
{
ulong av = 0;
for (int j = 0; j < 10; j++)
av += hist[i + j];
for (int j = 0; j < 10; j++)
average[i + j] = av / 10.0;
}
int windowSize = 31;
int win = windowSize >> 1;
for (int i = 0; i < size; i++)
{
int av = 0;
int ct = 0;
for (int j = i - win; j < i + win; j++)
{
if (j >= 0 && j < size)
{
av += hist[i+j];
ct++;
}
if (av > 0 && ct > 0)
average[i] = av / ct;
else
average[i] = MAXINT;
}
}
return average;
}
int* ImageProcessing::clusterMidPosition(int* hist, int size)
{
int* average = new int[size];
int lowerEstimate = MAXINT;
int higherEstimate = 0;
// limit to data range
for (int i = 0; i < size; i++)
{
higherEstimate = MAX(higherEstimate, hist[i]);
lowerEstimate = MIN(lowerEstimate, hist[i]);
}
int lowerCount = 1;
int higherCount = 1;
// get moving clusters
for (int i = 0; i < size; i++)
{
if (abs(hist[i] - lowerEstimate/lowerCount) < abs(hist[i] - higherEstimate/higherCount))
{
lowerEstimate += hist[i];
lowerCount++;
}
else
{
higherEstimate += hist[i];
higherCount++;
}
//if the difference between lower and higher is large enough then threshold is valid otherwise it should be background
average[i] = (higherEstimate / higherCount + lowerEstimate / lowerCount) / 2.0;
}
return average;
}
QString ImageProcessing::getBarcode(cv::Mat& src, QRect roi)
{
QString tag = "";
int width = src.cols;
int height = src.rows;
/// Detector parameters
cv::Mat gray = Mat::zeros(src.size(), CV_8UC1);
cv::Mat roiIm = src(cv::Rect(roi.x(), roi.y(), roi.width(), roi.height()));
if (src.channels() != 1)
cvtColor(roiIm, gray, CV_BGR2GRAY);
else
gray = roiIm;
ulong* hist = nullptr;
int size = 0;
if(roi.width()>roi.height())
{
size = gray.cols;
hist = new ulong[size];
// accumulate in columns
for (int i = 0; i < size; i++)
{
hist[i] = 0;
for (int j = 0; j < gray.rows; j++)
{
unsigned char g = gray.ptr<uchar>(j)[i];
hist[j] += g;
}
}
}
else
{
size = gray.rows;
hist = new ulong[size];
// accumulate in rows
for (int j = 0; j < size; j++)
{
hist[j] = 0;
for (int i = 0; i < gray.cols; i++)
{
unsigned char g = gray.ptr<uchar>(j)[i];
hist[j] += g;
}
}
}
QVector<ulong*> lines;
lines.append(hist);
cv::Mat im = HelperFunctions::linePlotImage<ulong>(lines, size, 1, 512, 512);
ulong f_min = hist[0], f_max = hist[0];
// find maximum/minimum
for (int i = 0; i < size; i++)
{
f_min = min(f_min, hist[i]);
f_max = max(f_max, hist[i]);
}
ulong mid = (f_max + f_min)>>1;
// threshold
for (int i = 0; i < size; i++)
{
QString s = QString::number(hist[i]);
DBOUT(s.data() << ", ");
tag += hist[i] > mid ? "1" : "0";
}
delete[] hist;
return tag;
}
/**
*
* Threshold image between min and max greyscale values
*
* Method: calibrateCamera
* FullName: ImageProcessing::calibrateCamera
* Access: public static
* Returns: void
* Qualifier:
* Parameter: std::vector<targeterImage> imageList
* Parameter: SettingsValues s
*/
void ImageProcessing::calibrateCamera(QVector<QExplicitlySharedDataPointer<targeterImage>> imageList, SettingsValues* s)
{
unsigned char flags = 0;
flags += s->bCV_CALIB_CB_ADAPTIVE_THRESH ? CALIB_CB_ADAPTIVE_THRESH : 0;
flags += s->bCV_CALIB_CB_NORMALIZE_IMAGE ? CALIB_CB_NORMALIZE_IMAGE : 0;
flags += s->bCV_CALIB_CB_FILTER_QUADS ? CALIB_CB_FILTER_QUADS : 0;
flags += s->bCALIB_CB_FAST_CHECK ? CALIB_CB_FAST_CHECK : 0;
unsigned char cal_flags = s->ZeroDistortion ? CALIB_ZERO_TANGENT_DIST : 0;
cal_flags += s->FixedAspect ? CALIB_FIX_ASPECT_RATIO : 0;
cal_flags += s->FixPrincipalPointCenter ? CALIB_FIX_PRINCIPAL_POINT : 0;
cal_flags += s->UseIntrinsicGuess ? CALIB_FIX_INTRINSIC : 0;
cal_flags += s->FixFocalLength ? CALIB_FIX_FOCAL_LENGTH : 0;
string str="";
if (flags != 0)
{
str += "corner detection flags = ";
str += ((flags & CALIB_CB_ADAPTIVE_THRESH) ? "adaptive threshold, " : "");
str += ((flags & CALIB_CB_NORMALIZE_IMAGE) ? "normalise image, " : "");
str += ((flags & CALIB_CB_FILTER_QUADS) ? "filter quads, " : "");
str += ((flags & CALIB_CB_FAST_CHECK) ? "fast check, " : "");
str += "\n";
}
if (cal_flags != 0)
{
str += "calibration flags = ";
str += ((cal_flags & CALIB_ZERO_TANGENT_DIST) ? "zero tangental distortion, " : "");
str += ((cal_flags & CALIB_FIX_ASPECT_RATIO) ? "fix aspect ratio, " : "");
str += ((cal_flags & CALIB_FIX_PRINCIPAL_POINT) ? "fix principal point, " : "");
str += ((cal_flags & CALIB_FIX_INTRINSIC) ? "fix intrinsics, " : "");
str += ((cal_flags & CALIB_FIX_FOCAL_LENGTH) ? "fix focal length" : "");
str += "\n";
}
DBOUT(str.data());
vector<vector<cv::Point2f>> image_points;
vector<vector<cv::Point3f>> object_points;
cv::Mat image;
cv::Size boardSize = cv::Size(s->calibrateNoRows, s->calibrateNoCols);
int board_n = s->calibrateNoRows * s->calibrateNoCols;
int n_boards = imageList.size();
cv::Size image_size;
float focalDist = s->activeCamera == cameraType::camera::microscope ? s->focalDistanceMicroscopeCamera : s->focalDistanceOverviewCamera;
//overview camera has 35mm lens
float FocalLengthInPixels = 1000.0*focalDist / s->mmPerPixel; // = 1000 * 35mm fl / 5.5um pixel size
if (imageList.size() == 0)
{
emit LOGCONSOLE("no images selected - exiting function", CONSOLECOLOURS::colour::Critical);
return;
}
foreach(targeterImage view, imageList)
{
cv::Mat& im = view.getImage();
image_size = im.size();
vector<cv::Point2f> corners;
bool bFound = false;
Mat viewGray;
switch (s->CalibrateAlgorithm) // Find feature points on the input format
{
case calibrateAlgoType::algoType::CHESSBOARD:
// also use our corner detection algorithm instead here (after editing corners)
bFound = cv::findChessboardCorners(im, boardSize, corners, flags);
cvtColor(im, viewGray, COLOR_BGR2GRAY);
if(bFound)
{
// extra accuracy on corner detection
cornerSubPix(viewGray, corners, Size(11, 11), Size(-1, -1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1));
}
break;
case calibrateAlgoType::algoType::CIRCLES_GRID:
bFound = findCirclesGrid(im, boardSize, corners, CALIB_CB_SYMMETRIC_GRID);
break;
case calibrateAlgoType::algoType::ASYMMETRIC_CIRCLES_GRID:
bFound = findCirclesGrid(im, boardSize, corners, CALIB_CB_ASYMMETRIC_GRID);
break;
default:
bFound = false;
break;
}
double squareSize = s->SizeOfSquare;
if (bFound)
{
image ^= cv::Scalar::all(255);
image_points.push_back(corners);
object_points.push_back(vector<Point3f>());
vector<cv::Point3f>& opts = object_points.back();
opts.resize(board_n);
switch (s->CalibrateAlgorithm) {
case calibrateAlgoType::CHESSBOARD:
case calibrateAlgoType::CIRCLES_GRID:
for (int i = 0; i < s->calibrateNoCols; i++)
for (int j = 0; j < s->calibrateNoRows; j++)
opts[i + j*s->calibrateNoCols] = cv::Point3f((float)(j*squareSize), (float)(i*squareSize), 0.f);
break;
case calibrateAlgoType::ASYMMETRIC_CIRCLES_GRID:
for (int i = 0; i < s->calibrateNoCols; i++)
for (int j = 0; j < s->calibrateNoRows; j++)
opts[i + j*s->calibrateNoCols] = cv::Point3f((float)((2 * j + i % 2)*squareSize), (float)(i*squareSize), 0.f);
break;
}
emit LOGCONSOLE("collected our " + QString::number(image_points.size()) + " of " + QString::number(n_boards) + " needed images");
}
else
{
std::string s = "did find chessboard corners in image " + view.name;
emit LOGCONSOLE(QString::fromStdString(s), CONSOLECOLOURS::colour::Warning);
}
}
if (image_points.size() == 0)
{
emit LOGCONSOLE("couldn't find any reference points in any image (check settings for the number of rows/cols in pattern) - exiting", CONSOLECOLOURS::colour::Question);
return;
}
emit LOGCONSOLE("calibrating the camera");
s->SizeOfSquare = 99;
FileStorage fs("temp", FileStorage::WRITE | FileStorage::MEMORY | FileStorage::FORMAT_YAML);
if (s->activeCamera == cameraType::overview)
{
s->calibrationDataOverview.intrinsic_matrix.at<float>(0, 0) = FocalLengthInPixels;
s->calibrationDataOverview.intrinsic_matrix.at<float>(1, 1) = FocalLengthInPixels;
double err = cv::calibrateCamera(object_points, image_points, image_size, s->calibrationDataOverview.intrinsic_matrix, s->calibrationDataOverview.distortion_coeffs, cv::noArray(), cv::noArray(), cal_flags);
fs << "overview camera reprojection_error" << err << "camera_matrix" << s->calibrationDataOverview.intrinsic_matrix << "distortion_coeffs" << s->calibrationDataOverview.distortion_coeffs;
}
else
{
s->calibrationDataMicroscope.intrinsic_matrix = cv::Mat(3, 3, CV_32F);
s->calibrationDataMicroscope.intrinsic_matrix.at<float>(0, 0) = FocalLengthInPixels;
s->calibrationDataMicroscope.intrinsic_matrix.at<float>(1, 1) = FocalLengthInPixels;
double err = cv::calibrateCamera(object_points, image_points, image_size, s->calibrationDataMicroscope.intrinsic_matrix, s->calibrationDataMicroscope.distortion_coeffs, cv::noArray(), cv::noArray(), cal_flags);
fs << "microscope camera reprojection_error" << err << "camera_matrix" << s->calibrationDataMicroscope.intrinsic_matrix << "distortion_coeffs" << s->calibrationDataMicroscope.distortion_coeffs;
}
std::string createdString = fs.releaseAndGetString();
emit LOGCONSOLE(QString::fromStdString(createdString), CONSOLECOLOURS::colour::Data);
}
cv::Mat ImageProcessing::CornerDetection(cv::Mat src, int noCorners)
{
Mat dst, dst_norm, dst_norm_scaled, src_gray;
dst = Mat::zeros(src.size(), CV_32FC1);
/// Detector parameters
cvtColor(src, src_gray, CV_BGR2GRAY);
/// Detecting corners
std::vector< cv::Point2f > corners;
double qualityLevel = 0.01;
double minDistance = 20.;
int blockSize = 3;
bool useHarrisDetector = true;
double k = 0.04;
cv::Mat mask;
//cornerHarris(src_gray, dst, blockSize, apertureSize, k, BORDER_DEFAULT);
goodFeaturesToTrack(src_gray, corners, noCorners, qualityLevel, minDistance, mask, blockSize, useHarrisDetector, k);
// refine corner detection
cornerSubPix(src_gray, corners, Size(11, 11), Size(-1, -1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1));
for (size_t i = 0; i < corners.size(); i++)
{
cv::circle(src, corners[i], 10, cv::Scalar(255.), 3);
}
return src;
}
void calculateSymetricPoint(Point const & inPoint, Point & outPoint, Size const & psize, int padding)
{
if (inPoint.y < padding)
outPoint.y = 2 * padding - inPoint.y - 1;
else if (inPoint.y > (psize.width - padding - 1))
outPoint.y = psize.width - 2 * padding + psize.width - inPoint.y - 1;
else
outPoint.y = inPoint.y;
if (inPoint.x < padding)
outPoint.x = 2 * padding - inPoint.x - 1;
else if (inPoint.x > (psize.height - padding - 1))
outPoint.x = psize.height - 2 * padding + psize.height - inPoint.x - 1;
else
outPoint.x = inPoint.x;
}
void ImageProcessing::symmetricPadding(Mat const & image, Mat & paddedImage, int padding)
{
//Padd with zeros
copyMakeBorder(image, paddedImage, padding, padding, padding, padding, 0);
MatIterator_<uchar> its;
MatIterator_<uchar> it;
Size psize = paddedImage.size();
for (unsigned int j = 0; j < psize.width; j++)
{
for (unsigned int i = 0; i < padding; i++)
{
Point sp;
Point p(i, j);
calculateSymetricPoint(p, sp, psize, padding);
its = paddedImage.begin<uchar>() + sp.x*paddedImage.cols + sp.y;
it = paddedImage.begin<uchar>() + p.x*paddedImage.cols + p.y;
*it = *its;
}
for (unsigned int i = psize.height - padding; i < psize.height; i++)
{
Point sp;
Point p(i, j);
calculateSymetricPoint(p, sp, psize, padding);
its = paddedImage.begin<uchar>() + sp.x*paddedImage.cols + sp.y;
it = paddedImage.begin<uchar>() + p.x*paddedImage.cols + p.y;
*it = *its;
}
}
for (unsigned int i = padding; i < psize.height - padding; i++)
{
for (unsigned int j = 0; j < padding; j++)
{
Point sp;
Point p(i, j);
calculateSymetricPoint(p, sp, psize, padding);
its = paddedImage.begin<uchar>() + sp.x*paddedImage.cols + sp.y;
it = paddedImage.begin<uchar>() + p.x*paddedImage.cols + p.y;
*it = *its;
}
for (unsigned int j = psize.width - padding; j < psize.width; j++)
{
Point sp;
Point p(i, j);
calculateSymetricPoint(p, sp, psize, padding);
its = paddedImage.begin<uchar>() + sp.x*paddedImage.cols + sp.y;
it = paddedImage.begin<uchar>() + p.x*paddedImage.cols + p.y;
*it = *its;
}
}
}
cv::Mat ImageProcessing::localMaxima(cv::Mat image,bool remove_plateaus)
{
cv::Mat mask;
// find pixels that are equal to the local neighborhood not maximum (including 'plateaus')
cv::dilate(image, mask, cv::Mat());
cv::compare(image, mask, mask, cv::CMP_GE);
// optionally filter out pixels that are equal to the local minimum ('plateaus')
if (remove_plateaus) {
cv::Mat non_plateau_mask;
cv::erode(image, non_plateau_mask, cv::Mat());
cv::compare(image, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
}
return mask;
}
double ImageProcessing::PointPairToBearingDegrees(cv::Point startingPoint, cv::Point endingPoint)
{
cv::Point originPoint = Point(endingPoint.x - startingPoint.x, endingPoint.y - startingPoint.y); // get origin point to origin by subtracting end from start
double bearingRadians = atan2f(originPoint.y, originPoint.x); // get bearing in radians
double bearingDegrees = bearingRadians * (180.0 / CV_PI); // convert to degrees
bearingDegrees = (bearingDegrees > 0.0 ? bearingDegrees : (360.0 + bearingDegrees)); // correct discontinuity
return bearingDegrees;
}
double ImageProcessing::imageMedian(cv::Mat channel)
{
double m = (channel.rows*channel.cols) / 2;
int bin = 0;
double med = -1.0;
int histSize = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
bool uniform = true;
bool accumulate = false;
cv::Mat hist;
cv::calcHist(&channel, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange, uniform, accumulate);
for (int i = 0; i < histSize && med < 0.0; ++i)
{
bin += cvRound(hist.at< float >(i));
if (bin > m && med < 0.0)
med = i;
}
return med;
}
double ImageProcessing::PointFromLine(cv::Point start, cv::Point end, cv::Point point)
{
double x0 = point.x;
double y0 = point.y;
double x1 = start.x;
double x2 = end.x;
double y1 = start.y;
double y2 = end.y;
double dx2 = (x2 - x1)*(x2 - x1);
double dy2 = (y2 - y1)*(y2 - y1);
double dis = fabs((y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 - y2*x1) / sqrt(dy2 + dx2);
return dis;
}
cv::Mat ImageProcessing::CannyEdgeDetection(cv::Mat& im, bool bConvertColor)
{
cv::Mat src;
Mat dst, cdst;
bool bAutomatic = true;
double goodFit = 0.1;
if (im.channels() > 2)
cv::cvtColor(im, src, cv::COLOR_BGR2GRAY);
else
src = im;
/// Remove noise by blurring with a Gaussian filter
cv::GaussianBlur(src, src, Size(3, 3), 0, 0, BORDER_DEFAULT);
// detect histogram peak
int v = imageMedian(src);
int lower = 15;
int upper = 50;
// apply automatic Canny edge detection using the computed median
if (bAutomatic) {
double sigma = 0.33;
lower = int(fmax(0, (1.0 - sigma) * v));
upper = int(fmin(255, (1.0 + sigma) * v));
}