-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathisp_lib.cpp
More file actions
972 lines (878 loc) · 28.5 KB
/
isp_lib.cpp
File metadata and controls
972 lines (878 loc) · 28.5 KB
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
/*****************************************************************************
* This file is part of the Linux Camera Tool
* Copyright (c) 2020 Leopard Imaging Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* This is the sample code for image signal processing library that used
* in this application.
*
* Author: Danyu L
* Last edit: 2019/08
*****************************************************************************/
#include "../includes/shortcuts.h"
#include "../includes/isp_lib.h"
#include "../includes/utility.h"
void tic(double &t)
{
t = (double)cv::getTickCount();
}
/**
* getTickcount: return number of ticks from OS
* getTickFrequency: returns the number of ticks per second
* t = ((double)getTickCount() - t)/getTickFrequency();
* fps is t's reciprocal
*/
double toc(double &t)
{
return ((double)cv::getTickCount() - t) / cv::getTickFrequency();
}
/**
* Apply gamma correction in-place for a given image array
* When *gamma_val < 1, the original dark regions will be brighter
* and the histogram will be shifted to the right
* Whereas it will be the opposite with *gamma_val > 1
* Recommend gamma_value: 0.45(1/2.2)
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
* int gamma_value - gamma value
*/
void apply_gamma_correction(
cv::InputOutputArray& opencvImage,
float gamma_value)
{
cv::Mat look_up_table(1, 256, CV_8U);
uchar *p = look_up_table.ptr();
for (int i = 0; i < 256; i++)
{
p[i] = cv::saturate_cast<uchar>(pow(i / 255.0, gamma_value) * 255.0);
}
#ifdef HAVE_OPENCV_CUDA_SUPPORT
cv::Ptr<cv::cuda::LookUpTable> lutAlg =
cv::cuda::createLookUpTable(look_up_table);
lutAlg->transform(opencvImage, opencvImage);
#else
LUT(opencvImage, look_up_table, opencvImage);
#endif
}
/**
* Apply auto white balance in-place for a given image array
* Ref: https://gist.github.com/tomykaira/94472e9f4921ec2cf582
*
* The basic idea of this AWB algorithm is
* 1. defining white as the highest values of R,G,B observed in the image
* 2. stretch as much as it can for rgb channels, so that they occupy
* maximal range by applying an affine transform ax+b to each channel.
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void apply_white_balance(
cv::InputOutputArray& opencvImage)
{
/// if it is gray image, do nothing
if (opencvImage.type() == CV_8UC1)
return;
#ifdef HAVE_OPENCV_CUDA_SUPPORT
cv::cuda::GpuMat _opencvImage = opencvImage.getGpuMat();
std::vector<cv::cuda::GpuMat> bgr_planes;
cv::cuda::split(_opencvImage, bgr_planes);
// cv::cuda::GpuMat hist[3];
// cv::Mat histogram[3];
// for (int i=0; i< 3; i++)
// {
// cv::cuda::calcHist(bgr_planes[i], hist[i]);
// hist[i].download(histogram[i]);
// }
// float accumulator[3][256];
// double discard_ratio = 0.05;
// int vmin[3], vmax[3];
// int total = _opencvImage.cols * _opencvImage.rows;
// for (int i = 0; i < 3; i++) {
// for (int j=0; j < (256-1); j++)
// {
// accumulator[i][j+1] = accumulator[i][j] + histogram[i].at<float>(j);
// }
// vmin[i] = 0;
// vmax[i] = 255;
// while (accumulator[i][vmin[i]] < discard_ratio * total)
// vmin[i] += 1;
// while (accumulator[i][vmax[i]] > (1 - discard_ratio) * total)
// vmax[i] -= 1;
// if (vmax[i] < 255 - 1)
// vmax[i] += 1;-
// }
// for(int i=0; i< 3; i++)
// {
// printf("vmin[%d]=%d\r\n", i, vmin[i]);
// //printf("vmax[%d]=%d\r\n", i, vmax[i]);
// }
cv::cuda::equalizeHist(bgr_planes[0], bgr_planes[0]);
cv::cuda::equalizeHist(bgr_planes[1], bgr_planes[1]);
cv::cuda::equalizeHist(bgr_planes[2], bgr_planes[2]);
cv::cuda::merge(bgr_planes, opencvImage);
#else
cv::Mat _opencvImage = opencvImage.getMat();
double discard_ratio = 0.05;
int vmin[3], vmax[3];
int total = _opencvImage.cols * _opencvImage.rows;
/// build cumulative histogram
/// method 1: naive pixel access
int hists[3][256];
CLEAR(hists);
for (int y = 0; y < _opencvImage.rows; y++)
{
uchar *ptr = _opencvImage.ptr<uchar>(y);
for (int x = 0; x < _opencvImage.cols; x++)
{
for (int j = 0; j < 3; ++j)
{
hists[j][ptr[x * 3 + j]] += 1;
}
}
}
/// method 2: pointer arithmetic
// int hists[3][256];
// Pixel* pixel = _opencvImage.ptr<Pixel>(0,0);
// const Pixel* endPixel = pixel + _opencvImage.cols * _opencvImage.rows;
// for (; pixel!= endPixel; pixel++)
// {
// hists[0][pixel->x] ++;
// hists[1][pixel->y] ++;
// hists[2][pixel->z] ++;
// }
/// method 3: use OpenCV calcHist to accelerate build histogram
// cv::Mat bgr_planes[3];
// cv::Mat hist[3];
// cv::split(_opencvImage, bgr_planes);
// float range[] = {0.0f,256.0f};
// const float *histRange = {range};
// int hist_size = 256;
// for (int i=0; i<3; i++)
// {
// cv::calcHist(
// &bgr_planes[i], // src(const Mat*)
// 1, // n_images
// 0, // channels(gray = 0)
// cv::Mat(), // mask (for ROI)
// hist[i], // Mat hist
// 1, // dimension
// &hist_size, // histSize = bins = 256
// &histRange); // ranges for pixel
// }
/// cumulative hist and search for vmin and vmax
/// method 1&2: use int hists[3][256] to accumulate and compare
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 255; ++j)
{
hists[i][j + 1] += hists[i][j];
}
vmin[i] = 0;
vmax[i] = 255;
while (hists[i][vmin[i]] < discard_ratio * total)
vmin[i] += 1;
while (hists[i][vmax[i]] > (1 - discard_ratio) * total)
vmax[i] -= 1;
if (vmax[i] < 255 - 1)
vmax[i] += 1;
}
/// method 3: use float accumulator[3][256] to accumulate and compare
// float accumulator[3][256];
// for (int i = 0; i < 3; i++) {
// for (int j=0; j < (hist_size-1); j++)
// {
// accumulator[i][j+1] = accumulator[i][j] + hist[i].at<float>(j);
// }
// vmin[i] = 0;
// vmax[i] = 255;
// while (accumulator[i][vmin[i]] < discard_ratio * total)
// vmin[i] += 1;
// while (accumulator[i][vmax[i]] > (1 - discard_ratio) * total)
// vmax[i] -= 1;
// if (vmax[i] < 255 - 1)
// vmax[i] += 1;
// }
/// original raw pointer access, slower
// for (int y = 0; y < _opencvImage.rows; ++y)
// {
// uchar *ptr = _opencvImage.ptr<uchar>(y);
// for (int x = 0; x < _opencvImage.cols; ++x)
// {
// for (int j = 0; j < 3; ++j)
// {
// int val = ptr[x * 3 + j];
// if (val < vmin[j])
// val = vmin[j];
// if (val > vmax[j])
// val = vmax[j];
// ptr[x * 3 + j] = static_cast<uchar>((val - vmin[j]) * 255.0 / (vmax[j] - vmin[j]));
// }
// }
// }
/// use lambda, faster
_opencvImage.forEach<Pixel> (
[&vmin, &vmax] (Pixel &ptr, const int *position) -> void {
/// saturate the pixels
int b = ptr.x < vmin[0] ? vmin[0] : ptr.x > vmax[0] ? vmax[0] : ptr.x;
int g = ptr.y < vmin[1] ? vmin[1] : ptr.y > vmax[1] ? vmax[1] : ptr.y;
int r = ptr.z < vmin[2] ? vmin[2] : ptr.z > vmax[2] ? vmax[2] : ptr.z;
/// rescale the pixels
ptr.x = static_cast<uchar>((b-vmin[0])*255.0/(vmax[0] - vmin[0]));
ptr.y = static_cast<uchar>((g-vmin[1])*255.0/(vmax[1] - vmin[1]));
ptr.z = static_cast<uchar>((r-vmin[2])*255.0/(vmax[2] - vmin[2]));
}
);
#endif
}
/**
* In-place automatic brightness and contrast optimization with
* optional histogram clipping. Looking at histogram, alpha operates
* as color range amplifier, beta operates as range shift.
* O(x,y) = alpha * I(x,y) + beta
* Automatic brightness and contrast optimization calculates
* alpha and beta so that the output range is 0..255.
* Ref: http://answers.opencv.org/question/75510/how-to-make-auto-adjustmentsbrightness-and-contrast-for-image-android-opencv-image-correction/
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
* float clipHistPercent - cut wings of histogram at given percent
* typical=>1, 0=>Disabled
*/
void apply_auto_brightness_and_contrast(
cv::InputOutputArray& opencvImage,
float clipHistPercent = 0)
{
int hist_size = 256;
float alpha, beta;
double min_gray = 0, max_gray = 0;
#ifndef HAVE_OPENCV_CUDA_SUPPORT
/// to calculate grayscale histogram
cv::Mat gray;
if (opencvImage.type() != CV_8UC1)
cv::cvtColor(opencvImage, gray, cv::COLOR_BGR2GRAY);
else
gray = opencvImage.getMat();
if (clipHistPercent == 0)
{
/// keep full available range
cv::minMaxLoc(
gray, // src
&min_gray, // double* minVal
&max_gray); // double* maxVal
}
else
{
/// the grayscale histogram
cv::Mat hist;
float range[] = {0, 256};
const float *histRange = {range};
cv::calcHist(
&gray, // src(const Mat*)
1, // n_images
0, // channels(gray = 0)
cv::Mat(), // mask (for ROI)
hist, // Mat hist
1, // dimension
&hist_size, // histSize = bins = 256
&histRange, // ranges_for_pixel
true, // bool uniform
false); // bool accumulate
/// calculate cumulative distribution from the histogram
std::vector<float> accumulator(hist_size);
accumulator[0] = hist.at<float>(0);
for (int i = 1; i < hist_size; i++)
accumulator[i] = accumulator[i - 1] + hist.at<float>(i);
/// locate points that cuts at required value
float max = accumulator.back();
clipHistPercent *= (max / 100.0); /// make percent as absolute
clipHistPercent /= 2.0; /// left and right wings
/// locate left cut
min_gray = 0;
while (accumulator[min_gray] < clipHistPercent)
min_gray++;
/// locate right cut
max_gray = hist_size - 1;
while (accumulator[max_gray] >= (max - clipHistPercent))
max_gray--;
}
cv::Mat _opencvImage = opencvImage.getMat();
#else
/// to calculate grayscale histogram
cv::cuda::GpuMat gray;
gray = opencvImage.getGpuMat();
if (opencvImage.type() != CV_8UC1)
cv::cuda::cvtColor(gray, gray, cv::COLOR_BGR2GRAY);
cv::Point minLoc, maxLoc;
if (clipHistPercent == 0)
{
/// keep full available range
cv::cuda::minMaxLoc(
gray, // src
&min_gray, // minVal
&max_gray, // maxVal
NULL, // Point* minLoc
NULL); // Point* maxLoc
}
else
{
/// the grayscale histogram
cv::cuda::GpuMat hist;
/**
* calculate histogram for 8-bit gray image
* hist is a one row, 256 column, CV_32SC1 type
*/
cv::cuda::calcHist(
gray, // src
hist); // output histogram
/// calculate cumulative distribution from the histogram
cv::Mat histogram;
hist.download(histogram);
std::vector<float> accumulator(hist_size);
accumulator[0] = histogram.at<float>(0);
for (int i = 1; i < hist_size; i++)
accumulator[i] = accumulator[i - 1] + histogram.at<float>(i);
/// locate points that cuts at required value
float max = accumulator.back();
clipHistPercent *= (max / 100.0); /// make percent as absolute
clipHistPercent /= 2.0; /// left and right wings
/// locate left cut
min_gray = 0;
while (accumulator[min_gray] < clipHistPercent)
min_gray++;
/// locate right cut
max_gray = hist_size - 1;
while (accumulator[max_gray] >= (max - clipHistPercent))
max_gray--;
}
cv::cuda::GpuMat _opencvImage = opencvImage.getGpuMat();
#endif
/// current range
float input_range = max_gray - min_gray;
/// alpha expands current range to histsize range
alpha = (hist_size - 1) / input_range;
/// beta shifts current range so that minGray will go to 0
beta = -min_gray * alpha;
/**
* Apply brightness and contrast normalization
* convertTo operates with saturate_cast
*/
_opencvImage.convertTo(
opencvImage, // dst
-1, // rtype, if negative, same as input matrix type
alpha,
beta);
}
/**
* Contrast Limited Adaptive Histogram Equalization) algorithm
* The algorithm used for OpenCV CUDA and normal is the same
* Steps:
* 1. if it is RGB image, convert image to lab color-space, jump to step 2
* 2. separate and get L channel of lab planes, jump tp step 4
* 3. if it is monochrome image, jump to step 4
* 4. apply adaptive historgram equalization(cv::createCLAHE etc)
* 5. convert the resulting Lab back to RGB, if it is mono, do nothing
* Ref: https://stackoverflow.com/questions/24341114/simple-illumination-correction-in-images-opencv-c
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void apply_clahe(
cv::InputOutputArray& opencvImage)
{
#ifdef HAVE_OPENCV_CUDA_SUPPORT
if (opencvImage.type() != CV_8UC1)
{
cv::cuda::GpuMat lab_image;
cv::cuda::cvtColor(opencvImage, lab_image, cv::COLOR_BGR2Lab);
/// Extract the L channel
std::vector<cv::cuda::GpuMat> lab_planes(3);
/// now we have the L image in lab_planes[0]
cv::cuda::split(lab_image, lab_planes);
/// apply the CLAHE algorithm to the L channel
cv::Ptr<cv::cuda::CLAHE> clahe = cv::cuda::createCLAHE();
clahe->setClipLimit(4);
cv::cuda::GpuMat dst;
clahe->apply(lab_planes[0], dst);
/// Merge the the color planes back into an Lab image
dst.copyTo(lab_planes[0]);
cv::cuda::merge(lab_planes, lab_image);
/// convert back to RGB
cv::cuda::cvtColor(lab_image, opencvImage, cv::COLOR_Lab2BGR);
}
else
{
cv::Ptr<cv::cuda::CLAHE> clahe = cv::cuda::createCLAHE();
clahe->setClipLimit(4);
clahe->apply(opencvImage, opencvImage);
}
#else
if (opencvImage.type() != CV_8UC1)
{
cv::Mat lab_image;
cv::cvtColor(opencvImage, lab_image, cv::COLOR_BGR2Lab);
/// Extract the L channel
std::vector<cv::Mat> lab_planes(3);
/// now we have the L image in lab_planes[0]
cv::split(lab_image, lab_planes);
/// apply the CLAHE algorithm to the L channel
cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE();
clahe->setClipLimit(4);
cv::Mat dst;
clahe->apply(lab_planes[0], dst);
/// Merge the the color planes back into an Lab image
dst.copyTo(lab_planes[0]);
cv::merge(lab_planes, lab_image);
/// convert back to RGB
cv::cvtColor(lab_image, opencvImage, cv::COLOR_Lab2BGR);
}
else
{
cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE();
clahe->setClipLimit(4);
clahe->apply(opencvImage, opencvImage);
}
#endif
}
/**
* apply sharpness filter to a given image
*
* ref: https://stackoverflow.com/questions/4993082/how-to-sharpen-an-image-in-opencv
* use the algorithm of un-sharp mask:
* 1. apply a Gaussian smoothing filter
* 2. subtract the smoothed version from the original image
* (in a weighted way so the values of a constant area remain constant)
* sharpness slide will work as the Gaussian blur parameter sigma
*
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions,
* int sharpness_val - sharpness value
*/
void sharpness_control(
cv::InputOutputArray& opencvImage,
int sharpness_val)
{
#ifndef HAVE_OPENCV_CUDA_SUPPORT
cv::Mat _opencvImage = opencvImage.getMat();
cv::Mat blurred;
cv::GaussianBlur(
_opencvImage, // src
blurred, // dst
cv::Size(0, 0), // ksize, if 0, will compute from sigma
sharpness_val); // sigma, Gaussian kernel std in X direction
/// dst = src1*alpha + src2*beta + gamma;
cv::addWeighted(
_opencvImage, // src1
1.5, // alpha
blurred, // src2
-0.5, // beta
0, // gamma
opencvImage); // dst
#else
if (sharpness_val > 16) sharpness_val = 16;
int ksize = 2*(sharpness_val)-1;
cv::cuda::GpuMat _opencvImage = opencvImage.getGpuMat();
cv::cuda::GpuMat blurred;
cv::Ptr<cv::cuda::Filter> filter =
cv::cuda::createGaussianFilter(
_opencvImage.type(), // srcType
blurred.type(), // dstType
cv::Size(ksize, ksize), // ksize
sharpness_val); // sigma, Gaussian kernel std in X
filter->apply(_opencvImage, blurred);
cv::cuda::addWeighted(
_opencvImage, // src1
1.5, // alpha
blurred, // src2
-0.5, // beta
0, // gamma
opencvImage); // dst
#endif
}
/**
* Canny edge detecter
*
* Ref: https://docs.opencv.org/3.4/da/d5c/tutorial_canny_detector.html
* Steps:
* 1. convert the image to monochrome
* 2. smooth the image using a box filter blur for noise reduction(ksize = 5)
* 3. compute gradient intensity representations of the image
* 4. apply threshold with hysteresis
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
* int edge_low_threshold - edge low threshold
*/
void canny_filter_control(
cv::InputOutputArray& opencvImage,
int edge_low_threshold)
{
const int ratio = 3;
const int kernel_size = 3;
#ifndef HAVE_OPENCV_CUDA_SUPPORT
cv::Mat _opencvImage = opencvImage.getMat();
cv::Mat edges;
cv::cvtColor(_opencvImage, edges, cv::COLOR_BGR2GRAY);
/// blur an image use normalized box filter
cv::blur(
edges, // src
edges, // dst
cv::Size(5,5)); // ksize
cv::Canny(
edges, // src
opencvImage, // dst
(edge_low_threshold), // threshold 1
(edge_low_threshold)*ratio, // threshold 2
kernel_size); // aperture size
#else
cv::cuda::GpuMat _opencvImage = opencvImage.getGpuMat();
cv::cuda::GpuMat edges;
cv::cuda::cvtColor(_opencvImage, edges, cv::COLOR_BGR2GRAY);
/// blur an image use normalized box filter
cv::Ptr<cv::cuda::Filter> blur =
cv::cuda::createBoxFilter(
edges.type(), // srcType
edges.type(), // dstType
cv::Size(5,5)); // ksize
blur->apply(
edges, // src
edges); // dst
cv::Ptr<cv::cuda::CannyEdgeDetector> canny =
cv::cuda::createCannyEdgeDetector(
(edge_low_threshold), // threshold 1
(edge_low_threshold)*ratio,// threshold 2
kernel_size); // aperture size
canny->detect(
edges, // src
opencvImage); // dst
#endif
}
/**
* ref: https://github.com/microsoft/Windows-universal-samples/blob/master/Samples/CameraOpenCV/shared/OpenCVBridge/OpenCVHelper.cpp
*/
void display_histogram(
cv::InputOutputArray& opencvImage)
{
/// if it is gray image, do nothing
if (opencvImage.type() == CV_8UC1)
return;
cv::Mat _opencvImage = opencvImage.getMat();
cv::Mat outputMat(_opencvImage.cols, _opencvImage.rows,CV_8UC3);
std::vector<cv::Mat> bgr_planes;
split(opencvImage, bgr_planes);
int histSize = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
cv::Mat b_hist, g_hist, r_hist;
calcHist(&bgr_planes[0], 1, 0, cv::Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate);
calcHist(&bgr_planes[1], 1, 0, cv::Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate);
calcHist(&bgr_planes[2], 1, 0, cv::Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate);
int hist_w = outputMat.cols; int hist_h = outputMat.rows;
double bin_w = (double)outputMat.cols / histSize;
normalize(b_hist, b_hist, 0, outputMat.rows, cv::NORM_MINMAX, -1, cv::Mat());
normalize(g_hist, g_hist, 0, outputMat.rows, cv::NORM_MINMAX, -1, cv::Mat());
normalize(r_hist, r_hist, 0, outputMat.rows, cv::NORM_MINMAX, -1, cv::Mat());
for (int i = 1; i < histSize; i++)
{
int x1 = cvRound(bin_w * (i - 1));
int x2 = cvRound(bin_w * i);
line(outputMat, cv::Point(x1, hist_h - cvRound(b_hist.at<float>(i - 1))),
cv::Point(x2, hist_h - cvRound(b_hist.at<float>(i))),
cv::Scalar(255, 0, 0, 255), 2, 8, 0);
line(outputMat, cv::Point(x1, hist_h - cvRound(g_hist.at<float>(i - 1))),
cv::Point(x2, hist_h - cvRound(g_hist.at<float>(i))),
cv::Scalar(0, 255, 0, 255), 2, 8, 0);
line(outputMat, cv::Point(x1, hist_h - cvRound(r_hist.at<float>(i - 1))),
cv::Point(x2, hist_h - cvRound(r_hist.at<float>(i))),
cv::Scalar(0, 0, 255, 255), 2, 8, 0);
}
cv::namedWindow("histogram",0);
cv::resizeWindow("histogram", 640, 480);
cv::imshow("histogram", outputMat);
}
/**
* ref: https://github.com/microsoft/Windows-universal-samples/blob/master/Samples/CameraOpenCV/shared/OpenCVBridge/OpenCVHelper.cpp
*/
void motion_detector(
cv::InputOutputArray& opencvImage)
{
cv::Ptr<cv::BackgroundSubtractor> pMOG2; //MOG Background subtractor
//Creates mixture-of-gaussian background subtractor
pMOG2 = cv::createBackgroundSubtractorMOG2(); //MOG2 approach
cv::Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method
pMOG2->apply(opencvImage, fgMaskMOG2);
// int type = fgMaskMOG2.type();
cv::Mat temp;
cv::cvtColor(fgMaskMOG2, temp, cv::COLOR_GRAY2BGRA);
cv::Mat element = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
erode(temp, temp, element);
temp.copyTo(opencvImage);
}
/**
* Separate display right and left mat image from a dual stereo vision camera
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void display_dual_stereo_separately(
cv::InputOutputArray& opencvImage)
{
cv::Mat _opencvImage = opencvImage.getMat();
/// define region of interest for cropped Mat for dual stereo
cv::Rect roi_left(
0, /// start_x
0, /// start_y
_opencvImage.cols/2, /// width
_opencvImage.rows); /// height
cv::Mat cropped_ref_left(_opencvImage, roi_left);
cv::Mat cropped_left;
cropped_ref_left.copyTo(cropped_left);
cv::imshow("cam_left", cropped_left);
cv::Rect roi_right(
_opencvImage.cols/2, /// start_x
0, /// start_y
_opencvImage.cols/2, /// width
_opencvImage.rows); /// height
cv::Mat cropped_ref_right(_opencvImage, roi_right);
cv::Mat cropped_right;
cropped_ref_right.copyTo(cropped_right);
cv::imshow("cam_right", cropped_right);
}
/**
* unify putting text in opencv image
* a wrapper for put_text()
* args:
* cv::Mat opencvImage - camera stream buffer array
* that can be modified inside the functions
* str - text you will put in
* cordinate_y - vertical location that will put this line
*/
void streaming_put_text(
cv::Mat &opencvImage,
const char *str,
int cordinate_y)
{
int scale = opencvImage.cols / 1000;
cv::putText(
opencvImage,
str,
cv::Point(scale * TEXT_SCALE_BASE, cordinate_y), // Coordinates
cv::FONT_HERSHEY_SIMPLEX, // Font
(float)scale, // Scale. 2.0 = 2x bigger
cv::Scalar(255, 255, 255), // BGR Color - white
2 // Line Thickness
); // Anti-alias (Optional)
}
/**
* put a given stream's info text in:
* res, fps, ESC,
* automatically adjust text size with different camera resolutions
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void display_current_mat_stream_info(
cv::InputOutputArray& opencvImage)
{
static struct timeval tv_pre;
static struct timeval tv_cur;
static int interval;
cv::Mat _opencvImage = opencvImage.getMat();
int height_scale = (_opencvImage.cols / 1000);
streaming_put_text(_opencvImage, "ESC: close application",
height_scale * TEXT_SCALE_BASE);
char resolution[25];
sprintf(resolution, "Current Res:%dx%d",
_opencvImage.cols, _opencvImage.rows);
streaming_put_text(_opencvImage, resolution,
height_scale * TEXT_SCALE_BASE * 2);
//double fps = 1.0 / toc(*cur_time);
struct timeval tv;
gettimeofday(&tv,NULL);
tv_cur = tv;
interval = (tv.tv_sec*1000+tv.tv_usec/1000) - (tv_pre.tv_sec*1000+tv_pre.tv_usec/1000);
tv_pre = tv;
double fps = ((float)1000)/((float)interval);
char string_frame_rate[10]; // string to save fps
sprintf(string_frame_rate, "%.2f", fps); // to 2 decimal places
char fpsString[20];
strcpy(fpsString, "Current Fps:");
strcat(fpsString, string_frame_rate);
streaming_put_text(_opencvImage, fpsString,
height_scale * TEXT_SCALE_BASE * 3);
}
/**
* Apply brightness(alpha) and contrast(beta) control from slider val
* for both color and mono camera stream
* histogram clipping. Looking at histogram, alpha operates
* as color range amplifier, beta operates as range shift.
* O(x,y) = alpha * I(x,y) + beta
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void apply_brightness_and_contrast(
cv::InputOutputArray& opencvImage,
int alpha_val,
int beta_val)
{
#ifndef HAVE_OPENCV_CUDA_SUPPORT
cv::Mat _opencvImage = opencvImage.getMat();
#else
cv::cuda::GpuMat _opencvImage = opencvImage.getGpuMat();
#endif
_opencvImage.convertTo(
opencvImage, // dst
-1, // rtype, if negative, same as input matrix type
alpha_val,
beta_val);
}
/**
* Debayer and apply AWB for a given frame(support both OpenCV CUDA and not)
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void debayer_awb_a_frame(
cv::InputOutputArray& opencvImage,
int bayer_flg,
int awb_flg)
{
/** color output */
if (bayer_flg != CV_MONO_FLG)
{
#ifdef HAVE_OPENCV_CUDA_SUPPORT
// cv::cuda::cvtColor(opencvImage, opencvImage,
// cv::COLOR_BayerBG2BGR + bayer_flg);
cv::cuda::demosaicing(opencvImage, opencvImage,
cv::cuda::COLOR_BayerBG2BGR_MHT + bayer_flg);
#else
cv::cvtColor(opencvImage, opencvImage,
cv::COLOR_BayerBG2BGR + bayer_flg);
#endif
if (awb_flg)
{
//Timer timer;
apply_white_balance(opencvImage);
}
}
/** mono output */
if (bayer_flg == CV_MONO_FLG && opencvImage.type() == CV_8UC3)
{
#ifdef HAVE_OPENCV_CUDA_SUPPORT
cv::cuda::cvtColor(opencvImage, opencvImage, cv::COLOR_BayerBG2BGR);
cv::cuda::cvtColor(opencvImage, opencvImage, cv::COLOR_BGR2GRAY);
#else
cv::cvtColor(opencvImage, opencvImage, cv::COLOR_BayerBG2BGR);
cv::cvtColor(opencvImage, opencvImage, cv::COLOR_BGR2GRAY);
#endif
}
}
/**
* In-place apply rgb color correction matrix for a given mat
* since this requires to access individual pixel of a given mat, OpenCV CUDA
* acceleration is not used
* For color correction matrix, please request from Leopard support
* Refs: http://www.imatest.com/docs/colormatrix/
* args:
* cv::InputOutputArray opencvImage - camera stream buffer array
* that can be modified inside the functions
*/
void apply_rgb_matrix_post_debayer(
cv::InputOutputArray& opencvImage,
int* ccm)
{
int rb = *ccm;
int rg = *(ccm+1);
int rr = *(ccm+2);
int gb = *(ccm+3);
int gg = *(ccm+4);
int gr = *(ccm+5);
int bb = *(ccm+6);
int bg = *(ccm+7);
int br = *(ccm+8);
cv::Mat _opencvImage = opencvImage.getMat();
/// method 1: raw pointer access, 150ms
// uchar r,g,b;
// for (int i=0; i < _opencvImage.rows;++i) {
// /// point to first pixel in row
// cv::Vec3b* pixel = _opencvImage.ptr<cv::Vec3b>(i);
// for (int j=0; j < _opencvImage.cols;++j) {
// r = pixel[j][2];
// g = pixel[j][1];
// b = pixel[j][0];
// pixel[j][2] = ((rb) * b + (rg) * g + (rr) * r)/256;
// pixel[j][1] = ((gb) * b + (gg) * g + (gr) * r)/256;
// pixel[j][0] = ((bb) * b + (bg) * g + (br) * r)/256;
// }
// }
/// method 2: raw pointer access, 60ms
// uchar r,g,b;
// for (int i=0; i < _opencvImage.rows;++i) {
// /// point to first pixel in row
// Pixel* ptr = _opencvImage.ptr<Pixel>(i);
// const Pixel* ptr_end = ptr + _opencvImage.cols;
// for (; ptr != ptr_end; ++ptr) {
// b = ptr->x;
// g = ptr->y;
// r = ptr->z;
// ptr->z = ((rb) * b + (rg) * g + (rr) * r)/256;
// ptr->y = ((gb) * b + (gg) * g + (gr) * r)/256;
// ptr->x = ((bb) * b + (bg) * g + (br) * r)/256;
// }
// }
/// method 3: using MatIterator, 150ms
// uchar r,g,b;
// for (Pixel &ptr : cv::Mat_<Pixel>(_opencvImage)) {
// b = ptr.x;
// g = ptr.y;
// r = ptr.z;
// ptr.z = ((rb) * b + (rg) * g + (rr) * r)/256;
// ptr.y = ((gb) * b + (gg) * g + (gr) * r)/256;
// ptr.x = ((bb) * b + (bg) * g + (br) * r)/256;
// }
/// method 4: using lambda, 18ms
/// capture everything by value
/// Pixel (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
_opencvImage.forEach<Pixel>(
[=] (Pixel &ptr, const int *position) -> void {
uchar b = ptr.x;
uchar g = ptr.y;
uchar r = ptr.z;
ptr.z = ((rb) * b + (rg) * g + (rr) * r)/256;
ptr.y = ((gb) * b + (gg) * g + (gr) * r)/256;
ptr.x = ((bb) * b + (bg) * g + (br) * r)/256;
}
);
}
/*
* decode the given input image and return cv::mat
* args:
* cv::InputOutputArray opencvImage
* return:
* cv::Mat img
*/
cv::Mat decode_mpeg_img(
cv::InputOutputArray opencvImage)
{
cv::Mat img;
img = cv::imdecode(opencvImage, cv::IMREAD_COLOR);
if (img.data == NULL)
{
printf("NULL in mjpeg image\r\n");
}
return img;
}