forked from MasteringOpenCV/code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageUtils_0.7.cpp
executable file
·2149 lines (1922 loc) · 85.5 KB
/
ImageUtils_0.7.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
/*****************************************************************************
* Face Recognition using Eigenfaces or Fisherfaces
******************************************************************************
* by Shervin Emami, 5th Dec 2012
* http://www.shervinemami.info/openCV.html
******************************************************************************
* Ch8 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
/*
* ImageUtils
* Handy utility functions for dealing with images in OpenCV (desktop or Android).
* by Shervin Emami ([email protected]), 27th May 2012.
* The most recent version of this will always be available from "http://shervinemami.info/openCV.html"
*/
#define USE_HIGHGUI // Enable this to display graph windows using OpenCV's HighGUI. (Supports Windows, Linux & Mac, but not iPhone).
#include "ImageUtils.h"
using namespace std;
// Print the label and then some text info about the IplImage properties, to LOG() for easy debugging.
void printImageInfo(const IplImage *image, const char *label)
{
string s = "";
char buff[1024];
if (label)
s = label + string(": ");
if (image) {
snprintf(buff, sizeof(buff), "[Image] = %dw%dh, %d channels of %dbit depth, widthStep=%d, origin=%d", image->width, image->height, image->nChannels, image->depth, image->widthStep, image->origin);
s += buff;
if (image->roi)
snprintf(buff, sizeof(buff), " ROI=[at %d,%d of size %dx%d, COI=%d].\n", image->roi->xOffset, image->roi->yOffset, image->roi->width, image->roi->height, image->roi->coi);
else
snprintf(buff, sizeof(buff), " ROI=<null>.\n");
s += buff;
}
else {
s = "[Image] = <null>\n";
}
// LOG can be printf or similar.
LOG(s.c_str());
}
// Print the pixel values of the IplImage, to LOG() for easy debugging.
void printImagePixels(const IplImage *image, const char *label, int maxElements )
{
string s;
char buff[32];
if (label)
s = label + string(": ");
else
s = "Image: ";
if (image) {
if (maxElements == 0)
maxElements = image->width * image->height;
sprintf(buff, "(%dw%dh):\n", image->width, image->height);
s += string(buff);
LOG(s.c_str());
int totalElements = 0;
int depth = image->depth & 255;
for (int row=0; row < image->height; row++) {
string s = "";
int element = 0;
if (image->nChannels > 1 && image->height > 1) {
snprintf(buff, sizeof(buff), "row%d: ", row);
}
for (int col=0; col < image->width; col++) {
if (image->nChannels > 1)
s += "[";
for (int ch=0; ch <= image->nChannels-1; ch++) {
if (ch > 0 || (image->nChannels == 1 && col != 0)) // Add a separator, except for the first element of this pixel or row.
s += ",";
// Allow to print just part of the image.
totalElements++;
if (totalElements > maxElements) {
// LOG can be printf or similar.
LOG("%s ... <just displaying the 1st %d entries from %d!>", s.c_str(), maxElements, image->width * image->height * image->nChannels);
return;
}
if (depth == 8) // 8-bit UCHAR image.
snprintf(buff, sizeof(buff), "%d", image->imageData[(row * (image->widthStep)) + (col*image->nChannels) + ch]);
else if (depth == 16) // 16-bit short image.
snprintf(buff, sizeof(buff), "%d", *(short*)(uchar*)&image->imageData[(row * image->widthStep) + ((col*image->nChannels) + ch) * sizeof(short)]);
else if (depth == 32) // 32-bit float image.
snprintf(buff, sizeof(buff), "%.3f", *(float*)(uchar*)&image->imageData[(row * image->widthStep) + ((col*image->nChannels) + ch) * sizeof(float)]);
else if (depth == 64) // 64-bit double image.
snprintf(buff, sizeof(buff), "%.4lf", *(double*)(uchar*)&image->imageData[(row * image->widthStep) + ((col*image->nChannels) + ch) * sizeof(double)]);
s += buff;
const int MAX_ELEMENTS_PER_LINE = 60; // Only print upto 30 numbers per LOG() statement, since Android can only handle about 250 characters per log line!
if (element > MAX_ELEMENTS_PER_LINE) {
// LOG can be printf or similar.
LOG(s.c_str());
s = "";
element = 0;
}
element++;
}
if (image->nChannels > 1)
s += "] ";
}
// LOG can be printf or similar.
LOG(s.c_str());
}
}
else {
LOG("[%s] = <null>!", s.c_str());
}
}
// Return the number of bits in each channel of the given Mat. ie: 8, 16, 32 or 64.
int getBitDepth(const cv::Mat M)
{
switch (CV_MAT_DEPTH(M.type())) {
case CV_8U:
case CV_8S:
return 8;
case CV_16U:
case CV_16S:
return 16;
case CV_32S:
case CV_32F:
return 32;
case CV_64F:
return 64;
}
return -1;
}
// Print the contents of a multi-channel array (using "LOG()") for easy debugging.
// If 'maxElements' is 0, it will print the whole array. If it is -1, it will not print the array at all.
void printArray2D(const uchar *data, int cols, int rows, int channels, int depth_type, int step, int maxElements)
{
char buff[32];
if (data != 0 && cols > 0 && rows > 0 && channels > 0 && step > 0) {
// Show the actual data values
if (maxElements >= 0) {
if (maxElements == 0)
maxElements = rows * cols;
int totalElements = 0;
//int step = step;
for (int row=0; row < rows; row++) {
string s = "";
int element = 0;
if (channels > 1 && rows > 1) {
snprintf(buff, sizeof(buff), "row%d: ", row);
}
for (int col=0; col < cols; col++) {
if (channels > 1)
s += "[";
for (int ch=0; ch <= channels-1; ch++) {
if (ch > 0 || (channels == 1 && col != 0)) // Add a separator, except for the first element of this pixel or row.
s += ",";
buff[0] = '?'; // Initialize the string to "?" if something goes wrong.
buff[1] = 0;
// Allow to print just part of the image.
totalElements++;
if (totalElements > maxElements) {
// LOG can be printf or similar.
LOG("%s ... <just displaying the 1st %d entries from %d!>", s.c_str(), maxElements, rows * cols * channels);
return;
}
switch (depth_type) {
case CV_8U:
case CV_8S: // 8-bit UCHAR Mat.
snprintf(buff, sizeof(buff), "%d", data[(row * step) + (col*channels) + ch]);
break;
case CV_16U:
case CV_16S: // 16-bit short Mat.
snprintf(buff, sizeof(buff), "%d", *(short*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(short)]);
break;
case CV_32S: // 32-bit int Mat.
snprintf(buff, sizeof(buff), "%d", *(int*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(int)]);
break;
case CV_32F: // 32-bit float Mat.
snprintf(buff, sizeof(buff), "%.3f", *(float*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(float)]);
break;
case CV_64F: // 64-bit double Mat.
snprintf(buff, sizeof(buff), "%.3lg", *(double*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(double)]);
break;
default:
snprintf(buff, sizeof(buff), "UNKNOWN DEPTH OF %d!", depth_type);
}
s += buff;
const int MAX_ELEMENTS_PER_LINE = 30; // Only print upto 30 numbers per LOG() statement, since Android can only handle about 250 characters per log line!
if (element > MAX_ELEMENTS_PER_LINE) {
// LOG can be printf or similar.
LOG(s.c_str());
s = "";
element = 0;
}
element++;
}
if (channels > 1)
s += "] ";
}
// LOG can be printf or similar.
LOG(s.c_str());
}
}//end if (maxElements>=0)
}
}
// Print the label and then contents of a cv::Mat from the C++ interface (using "LOG()") for easy debugging.
// If 'maxElements' is 0, it will print the whole array. If it is -1, it will not print the array at all.
void printMat(const cv::Mat M, const char *label, int maxElements)
{
string s;
char buff[32];
if (label)
s = label + string(": ");
else
s = "Mat: ";
if (!M.empty()) {
int channels = CV_MAT_CN(M.type());
int depth_bpp = getBitDepth(M); // eg: 8, 16, 32.
int depth_type = CV_MAT_DEPTH(M.type()); // eg: CV_32S, CV_32F
// Show the dimensions & data type
sprintf(buff, "%dw%dh %dch %dbpp", M.cols, M.rows, channels, depth_bpp);
s += string(buff);
// Show the data range for each channel
s += ", range";
for (int ch=0; ch<channels; ch++) {
cv::Mat arr = cv::Mat(M.rows, M.cols, depth_type);
// Extract one channel at a time, to show it's range.
int from_to[2];
from_to[0] = ch;
from_to[1] = 0;
cv::mixChannels( &M, 1, &arr, 1, from_to, 1 );
// Show it's range.
double minVal, maxVal;
cv::minMaxLoc(arr, &minVal, &maxVal);
snprintf(buff, sizeof(buff), "[%lg,%lg]", minVal, maxVal);
s += buff;
}
LOG(s.c_str());
// Show the actual data values
printArray2D(M.data, M.cols, M.rows, channels, depth_type, M.step, maxElements);
}
else {
LOG("%s empty Mat", s.c_str());
}
}
// Print the label and info of a cv::Mat from the C++ interface (using "LOG()") for easy debugging.
void printMatInfo(const cv::Mat M, const char *label)
{
printMat(M, label, -1);
}
// Print the label and then contents of a cvMat from the C interface (using "LOG()") for easy debugging.
void printMatrix(const CvMat *M, const char *label, int maxElements)
{
string s;
char buff[32];
if (label)
s = label + string(": ");
else
s = "Matrix: ";
if (M) {
if (maxElements == 0)
maxElements = M->rows * M->cols;
sprintf(buff, "[%drows x %dcols]:\n", M->rows, M->cols);
s += string(buff);
LOG(s.c_str());
int channels = CV_MAT_CN(M->type);
int depth = CV_MAT_DEPTH(M->type);
int totalElements = 0;
uchar *data = (uchar*)M->data.ptr;
int step = M->step;
for (int row=0; row < M->rows; row++) {
string s = "";
int element = 0;
if (channels > 1 && M->rows > 1) {
snprintf(buff, sizeof(buff), "row%d: ", row);
}
for (int col=0; col < M->cols; col++) {
if (channels > 1)
s += "[";
for (int ch=0; ch <= channels-1; ch++) {
if (ch > 0 || (channels == 1 && col != 0)) // Add a separator, except for the first element of this pixel or row.
s += ",";
buff[0] = '?'; // Initialize the string to "?" if something goes wrong.
buff[1] = 0;
// Allow to print just part of the image.
totalElements++;
if (totalElements > maxElements) {
// LOG can be printf or similar.
LOG("%s ... <just displaying the 1st %d entries from %d!>", s.c_str(), maxElements, M->rows * M->cols * channels);
return;
}
switch (depth) {
case CV_8U:
case CV_8S: // 8-bit UCHAR Mat.
buff[0] = 'C';
//snprintf(buff, sizeof(buff), "%d", data[(row * step) + (col*channels) + ch]);
; // UNTESTED!
break;
case CV_16U:
case CV_16S: // 16-bit short Mat.
buff[0] = 'S';
//snprintf(buff, sizeof(buff), "%d", *(short*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(short)]);
; // UNTESTED!
break;
case CV_32S: // 32-bit int Mat.
buff[0] = 'I';
snprintf(buff, sizeof(buff), "%d", *(int*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(int)]);
; // UNTESTED!
break;
case CV_32F: // 32-bit float Mat.
snprintf(buff, sizeof(buff), "%.3f", *(float*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(float)]);
break;
case CV_64F: // 64-bit double Mat.
buff[0] = 'D';
//snprintf(buff, sizeof(buff), "%.4lf", *(double*)(uchar*)&data[(row * step) + ((col*channels) + ch) * sizeof(double)]);
; // UNTESTED!
break;
default:
snprintf(buff, sizeof(buff), "UNKNOWN DEPTH OF %d!", depth);
}
s += buff;
const int MAX_ELEMENTS_PER_LINE = 60; // Only print upto 30 numbers per LOG() statement, since Android can only handle about 250 characters per log line!
if (element > MAX_ELEMENTS_PER_LINE) {
// LOG can be printf or similar.
LOG(s.c_str());
s = "";
element = 0;
}
element++;
}
if (channels > 1)
s += "] ";
}
// LOG can be printf or similar.
LOG(s.c_str());
}
}
else {
LOG("[%s] = <null>!", s.c_str());
}
}
// Print the x & y coords of the given point. If 'label' is supplied, prints that first, and also prints a newline character on the end.
void printPoint32f(const CvPoint2D32f pt, const char *label)
{
if (label)
cout << label << ": ";
cout << "(" << pt.x << ", " << pt.y << ")";
if (label)
cout << endl;
}
// Print the start & end coords of the given line. If 'label' is supplied, prints that first, and also prints a newline character on the end.
void printLine(const CvPoint ptA, const CvPoint ptB, const char *label)
{
if (label)
cout << label << ": ";
cout << "(" << ptA.x << ", " << ptA.y << ")-(" << ptB.x << ", " << ptB.y << ")";
if (label)
cout << endl;
}
// Just for debugging float images & matrices.
void printDataRange(const CvArr *src, const char *msg)
{
if (((IplImage*)src)->nChannels == 2) { // 2-ch (Complex) input
double min_val[2] = {0};
double max_val[2] = {0};
IplImage * imgComplexSrcRe = cvCreateImage( cvGetSize(((IplImage*)src)), IPL_DEPTH_32F, 1 );
IplImage * imgComplexSrcIm = cvCreateImage( cvGetSize(((IplImage*)src)), IPL_DEPTH_32F, 1 );
cvSplit(src, imgComplexSrcRe, imgComplexSrcIm, NULL, NULL);
cvMinMaxLoc(imgComplexSrcRe, &min_val[0], &max_val[0], NULL, NULL, NULL);
cvMinMaxLoc(imgComplexSrcIm, &min_val[1], &max_val[1], NULL, NULL, NULL);
LOG("\t`` %s Range: Complex MIN = %lf %lfj, MAX = %lf %lfj", msg, min_val[0], min_val[1], max_val[0], max_val[1]);
cvReleaseImage(&imgComplexSrcRe);
cvReleaseImage(&imgComplexSrcIm);
}
else if (((IplImage*)src)->nChannels == 1) { // 1-ch (Real) input
double min_val[1] = {0};
double max_val[1] = {0};
cvMinMaxLoc(src, &min_val[0], &max_val[0], NULL, NULL, NULL);
LOG("\t`` %s Range: Real MIN = %lf, MAX = %lf", msg, min_val[0], max_val[0]);
}
else {
LOG("\t`` %s Range: UNKNOWN because nChannels == %d != 1 or 2", msg, ((IplImage*)src)->nChannels);
}
}
//------------------------------------------------------------------------------
// Graphing functions
//------------------------------------------------------------------------------
const CvScalar BLACK = CV_RGB(0,0,0);
const CvScalar WHITE = CV_RGB(255,255,255);
const CvScalar GREY = CV_RGB(150,150,150);
int countGraph = 0; // Used by 'getGraphColor()'
CvScalar customGraphColor;
int usingCustomGraphColor = 0;
// Get a new color to draw graphs. Will use the latest custom color, or change between blue, green, red, dark-blue, dark-green and dark-red until a new image is created.
CvScalar getGraphColor(void)
{
if (usingCustomGraphColor) {
usingCustomGraphColor = 0;
return customGraphColor;
}
countGraph++;
switch (countGraph) {
case 1: return CV_RGB(60,60,255); // light-blue
case 2: return CV_RGB(60,255,60); // light-green
case 3: return CV_RGB(255,60,40); // light-red
case 4: return CV_RGB(0,210,210); // blue-green
case 5: return CV_RGB(180,210,0); // red-green
case 6: return CV_RGB(210,0,180); // red-blue
case 7: return CV_RGB(0,0,185); // dark-blue
case 8: return CV_RGB(0,185,0); // dark-green
case 9: return CV_RGB(185,0,0); // dark-red
default:
countGraph = 0; // start rotating through colors again.
return CV_RGB(200,200,200); // grey
}
}
// Call 'setGraphColor()' to reset the colors that will be used for graphs.
void setGraphColor(int index)
{
countGraph = index;
usingCustomGraphColor = 0; // dont use a custom color.
}
// Specify the exact color that the next graph should be drawn as.
void setCustomGraphColor(int R, int B, int G)
{
customGraphColor = CV_RGB(R, G, B);
usingCustomGraphColor = 1; // show that it will be used.
}
// Draw the graph of an array of floats into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawFloatGraph(const float *arraySrc, int nArrayLength, IplImage *imageDst, float minV, float maxV, int width, int height, char *graphLabel, bool showScale)
{
int w = width;
int h = height;
int b = 10; // border around graph within the image
if (w <= 20)
w = nArrayLength + b*2; // width of the image
if (h <= 20)
h = 220;
int s = h - b*2;// size of graph height
float xscale = 1.0;
if (nArrayLength > 1)
xscale = (w - b*2) / (float)(nArrayLength-1); // horizontal scale
IplImage *imageGraph; // output image
// Get the desired image to draw into.
if (!imageDst) {
// Create an RGB image for graphing the data
imageGraph = cvCreateImage(cvSize(w,h), 8, 3);
// Clear the image
cvSet(imageGraph, WHITE);
}
else {
// Draw onto the given image.
imageGraph = imageDst;
}
if (!imageGraph) {
cerr << "ERROR in drawFloatGraph(): Couldn't create image of " << w << " x " << h << endl;
exit(1);
}
CvScalar colorGraph = getGraphColor(); // use a different color each time.
// If the user didnt supply min & mav values, find them from the data, so we can draw it at full scale.
if (fabs(minV) < 0.0000001f && fabs(maxV) < 0.0000001f) {
for (int i=0; i<nArrayLength; i++) {
float v = (float)arraySrc[i];
if (v < minV)
minV = v;
if (v > maxV)
maxV = v;
}
}
float diffV = maxV - minV;
if (diffV == 0)
diffV = 0.00000001f; // Stop a divide-by-zero error
float fscale = (float)s / diffV;
// Draw the horizontal & vertical axis
int y0 = cvRound(minV*fscale);
cvLine(imageGraph, cvPoint(b,h-(b-y0)), cvPoint(w-b, h-(b-y0)), BLACK);
cvLine(imageGraph, cvPoint(b,h-(b)), cvPoint(b, h-(b+s)), BLACK);
// Write the scale of the y axis
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1
if (showScale) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.5,0.6, 0,1, CV_AA); // For OpenCV 2.0
CvScalar clr = GREY;
char text[16];
snprintf(text, sizeof(text)-1, "%.1f", maxV);
cvPutText(imageGraph, text, cvPoint(1, b+4), &font, clr);
// Write the scale of the x axis
snprintf(text, sizeof(text)-1, "%d", (nArrayLength-1) );
cvPutText(imageGraph, text, cvPoint(w-b+4-5*strlen(text), (h/2)+10), &font, clr);
}
// Draw the values
CvPoint ptPrev = cvPoint(b,h-(b-y0)); // Start the lines at the 1st point.
for (int i=0; i<nArrayLength; i++) {
int y = cvRound((arraySrc[i] - minV) * fscale); // Get the values at a bigger scale
int x = cvRound(i * xscale);
CvPoint ptNew = cvPoint(b+x, h-(b+y));
cvLine(imageGraph, ptPrev, ptNew, colorGraph, 1, CV_AA); // Draw a line from the previous point to the new point
ptPrev = ptNew;
}
// Write the graph label, if desired
if (graphLabel != NULL && strlen(graphLabel) > 0) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN, 0.5,0.7, 0,1,CV_AA);
cvPutText(imageGraph, graphLabel, cvPoint(30, 10), &font, CV_RGB(0,0,0)); // black text
}
return imageGraph;
}
// Draw the graph of an array of ints into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawIntGraph(const int *arraySrc, int nArrayLength, IplImage *imageDst, int minV, int maxV, int width, int height, char *graphLabel, bool showScale)
{
int w = width;
int h = height;
int b = 10; // border around graph within the image
if (w <= 20)
w = nArrayLength + b*2; // width of the image
if (h <= 20)
h = 220;
int s = h - b*2;// size of graph height
float xscale = 1.0;
if (nArrayLength > 1)
xscale = (w - b*2) / (float)(nArrayLength-1); // horizontal scale
IplImage *imageGraph; // output image
// Get the desired image to draw into.
if (!imageDst) {
// Create an RGB image for graphing the data
imageGraph = cvCreateImage(cvSize(w,h), 8, 3);
// Clear the image
cvSet(imageGraph, WHITE);
}
else {
// Draw onto the given image.
imageGraph = imageDst;
}
if (!imageGraph) {
cerr << "ERROR in drawIntGraph(): Couldn't create image of " << w << " x " << h << endl;
exit(1);
}
CvScalar colorGraph = getGraphColor(); // use a different color each time.
// If the user didnt supply min & mav values, find them from the data, so we can draw it at full scale.
if (minV == 0 && maxV == 0) {
for (int i=0; i<nArrayLength; i++) {
int v = arraySrc[i];
if (v < minV)
minV = v;
if (v > maxV)
maxV = v;
}
}
int diffV = maxV - minV;
if (diffV == 0)
diffV = 1; // Stop a divide-by-zero error
float fscale = (float)s / (float)diffV;
// Draw the horizontal & vertical axis
int y0 = cvRound(minV*fscale);
cvLine(imageGraph, cvPoint(b,h-(b-y0)), cvPoint(w-b, h-(b-y0)), BLACK);
cvLine(imageGraph, cvPoint(b,h-(b)), cvPoint(b, h-(b+s)), BLACK);
// Write the scale of the y axis
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1
if (showScale) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.5,0.6, 0,1, CV_AA); // For OpenCV 2.0
CvScalar clr = GREY;
char text[16];
snprintf(text, sizeof(text)-1, "%.1f", maxV);
cvPutText(imageGraph, text, cvPoint(1, b+4), &font, clr);
// Write the scale of the x axis
snprintf(text, sizeof(text)-1, "%d", (nArrayLength-1) );
cvPutText(imageGraph, text, cvPoint(w-b+4-5*strlen(text), (h/2)+10), &font, clr);
}
// Draw the values
CvPoint ptPrev = cvPoint(b,h-(b-y0)); // Start the lines at the 1st point.
for (int i=0; i<nArrayLength; i++) {
int y = cvRound((arraySrc[i] - minV) * fscale); // Get the values at a bigger scale
int x = cvRound(i * xscale);
CvPoint ptNew = cvPoint(b+x, h-(b+y));
cvLine(imageGraph, ptPrev, ptNew, colorGraph, 1, CV_AA); // Draw a line from the previous point to the new point
ptPrev = ptNew;
}
// Write the graph label, if desired
if (graphLabel != NULL && strlen(graphLabel) > 0) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN, 0.5,0.7, 0,1,CV_AA);
cvPutText(imageGraph, graphLabel, cvPoint(30, 10), &font, CV_RGB(0,0,0)); // black text
}
return imageGraph;
}
// Draw the graph of an array of uchars into imageDst or a new image, between minV & maxV if given..
// Remember to free the newly created image if imageDst is not given.
IplImage* drawUCharGraph(const uchar *arraySrc, int nArrayLength, IplImage *imageDst, int minV, int maxV, int width, int height, char *graphLabel, bool showScale)
{
int w = width;
int h = height;
int b = 10; // border around graph within the image
if (w <= 20)
w = nArrayLength + b*2; // width of the image
if (h <= 20)
h = 220;
int s = h - b*2;// size of graph height
float xscale = 1.0;
if (nArrayLength > 1)
xscale = (w - b*2) / (float)(nArrayLength-1); // horizontal scale
IplImage *imageGraph; // output image
// Get the desired image to draw into.
if (!imageDst) {
// Create an RGB image for graphing the data
imageGraph = cvCreateImage(cvSize(w,h), 8, 3);
// Clear the image
cvSet(imageGraph, WHITE);
}
else {
// Draw onto the given image.
imageGraph = imageDst;
}
if (!imageGraph) {
cerr << "ERROR in drawUCharGraph(): Couldn't create image of " << w << " x " << h << endl;
exit(1);
}
CvScalar colorGraph = getGraphColor(); // use a different color each time.
// If the user didnt supply min & mav values, find them from the data, so we can draw it at full scale.
if (minV == 0 && maxV == 0) {
for (int i=0; i<nArrayLength; i++) {
int v = arraySrc[i];
if (v < minV)
minV = v;
if (v > maxV)
maxV = v;
}
}
int diffV = maxV - minV;
if (diffV == 0)
diffV = 1; // Stop a divide-by-zero error
float fscale = (float)s / (float)diffV;
// Draw the horizontal & vertical axis
int y0 = cvRound(minV*fscale);
cvLine(imageGraph, cvPoint(b,h-(b-y0)), cvPoint(w-b, h-(b-y0)), BLACK);
cvLine(imageGraph, cvPoint(b,h-(b)), cvPoint(b, h-(b+s)), BLACK);
// Write the scale of the y axis
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1
if (showScale) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.5,0.6, 0,1, CV_AA); // For OpenCV 2.0
CvScalar clr = GREY;
char text[16];
snprintf(text, sizeof(text)-1, "%.1f", maxV);
cvPutText(imageGraph, text, cvPoint(1, b+4), &font, clr);
// Write the scale of the x axis
snprintf(text, sizeof(text)-1, "%d", (nArrayLength-1) );
cvPutText(imageGraph, text, cvPoint(w-b+4-5*strlen(text), (h/2)+10), &font, clr);
}
// Draw the values
CvPoint ptPrev = cvPoint(b,h-(b-y0)); // Start the lines at the 1st point.
for (int i=0; i<nArrayLength; i++) {
int y = cvRound((arraySrc[i] - minV) * fscale); // Get the values at a bigger scale
int x = cvRound(i * xscale);
CvPoint ptNew = cvPoint(b+x, h-(b+y));
cvLine(imageGraph, ptPrev, ptNew, colorGraph, 1, CV_AA); // Draw a line from the previous point to the new point
ptPrev = ptNew;
}
// Write the graph label, if desired
if (graphLabel != NULL && strlen(graphLabel) > 0) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN, 0.5,0.7, 0,1,CV_AA);
cvPutText(imageGraph, graphLabel, cvPoint(30, 10), &font, CV_RGB(0,0,0)); // black text
}
return imageGraph;
}
// Display a graph of the given float array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawFloatGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showFloatGraph(const char *name, const float *arraySrc, int nArrayLength, int delay_ms, IplImage *background)
{
#ifdef USE_HIGHGUI
// Draw the graph
IplImage *imageGraph = drawFloatGraph(arraySrc, nArrayLength, background);
// Display the graph into a window
cvNamedWindow( name );
cvShowImage( name, imageGraph );
cvWaitKey( 10 ); // Note that cvWaitKey() is required for the OpenCV window to show!
cvWaitKey( delay_ms ); // Wait longer to make sure the user has seen the graph
cvReleaseImage(&imageGraph);
#endif
}
// Display a graph of the given int array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawIntGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showIntGraph(const char *name, const int *arraySrc, int nArrayLength, int delay_ms, IplImage *background)
{
#ifdef USE_HIGHGUI
// Draw the graph
IplImage *imageGraph = drawIntGraph(arraySrc, nArrayLength, background);
// Display the graph into a window
cvNamedWindow( name );
cvShowImage( name, imageGraph );
cvWaitKey( 10 ); // Note that cvWaitKey() is required for the OpenCV window to show!
cvWaitKey( delay_ms ); // Wait longer to make sure the user has seen the graph
cvReleaseImage(&imageGraph);
#endif
}
// Display a graph of the given unsigned char array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawUCharGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showUCharGraph(const char *name, const uchar *arraySrc, int nArrayLength, int delay_ms, IplImage *background)
{
#ifdef USE_HIGHGUI
// Draw the graph
IplImage *imageGraph = drawUCharGraph(arraySrc, nArrayLength, background);
// Display the graph into a window
cvNamedWindow( name );
cvShowImage( name, imageGraph );
cvWaitKey( 10 ); // Note that cvWaitKey() is required for the OpenCV window to show!
cvWaitKey( delay_ms ); // Wait longer to make sure the user has seen the graph
cvReleaseImage(&imageGraph);
#endif
}
// Simple helper function to easily view an image, with an optional pause.
void showImage(const IplImage *img, int delay_ms, char *name)
{
/*
#ifdef USE_HIGHGUI
if (!name)
name = "Image";
cvNamedWindow(name, CV_WINDOW_AUTOSIZE);
cvShowImage(name, img);
cvWaitKey(delay_ms);
#endif
*/
}
//------------------------------------------------------------------------------
// Color conversion functions
//------------------------------------------------------------------------------
// Return a new image that is always greyscale, whether the input image was RGB or Greyscale.
// Remember to free the returned image using cvReleaseImage() when finished.
IplImage* convertImageToGreyscale(const IplImage *imageSrc)
{
IplImage *imageGrey;
// Either convert the image to greyscale, or make a copy of the existing greyscale image.
// This is to make sure that the user can always call cvReleaseImage() on the output, whether it was greyscale or not.
if (imageSrc->nChannels == 3) {
imageGrey = cvCreateImage( cvGetSize(imageSrc), IPL_DEPTH_8U, 1 );
cvCvtColor( imageSrc, imageGrey, CV_BGR2GRAY );
}
else {
imageGrey = cvCloneImage(imageSrc);
}
return imageGrey;
}
// Do the color conversion of a single pixel, from RGB to HSV using Hue values between 0 to 255, whereas OpenCV only allows Hues up to 180 instead of 255.
// ref: "http://cs.haifa.ac.il/hagit/courses/ist/Lectures/Demos/ColorApplet2/t_convert.html"
inline void convertPixelRGBtoHSV_256(int bR, int bG, int bB, int &bH, int &bS, int &bV)
{
float fR, fG, fB;
float fH, fS, fV;
const float FLOAT_TO_BYTE = 255.0f;
const float BYTE_TO_FLOAT = 1.0f / FLOAT_TO_BYTE;
// Convert from 8-bit integers to floats
fR = bR * BYTE_TO_FLOAT;
fG = bG * BYTE_TO_FLOAT;
fB = bB * BYTE_TO_FLOAT;
// Convert from RGB to HSV, using float ranges 0.0 to 1.0
float fDelta;
float fMin, fMax;
int iMax;
// Get the min & max, but use integer comparisons for slight speedup
if (bB < bG) {
if (bB < bR) {
fMin = fB;
if (bR > bG) {
iMax = bR;
fMax = fR;
}
else {
iMax = bG;
fMax = fG;
}
}
else {
fMin = fR;
fMax = fG;
iMax = bG;
}
}
else {
if (bG < bR) {
fMin = fG;
if (bB > bR) {
fMax = fB;
iMax = bB;
}
else {
fMax = fR;
iMax = bR;
}
}
else {
fMin = fR;
fMax = fB;
iMax = bB;
}
}
fDelta = fMax - fMin;
fV = fMax; // Value (Brightness).
if (iMax != 0) { // Make sure its not pure black.
fS = fDelta / fMax; // Saturation.
float ANGLE_TO_UNIT = 1.0f / (6.0f * fDelta); // Make the Hues between 0.0 to 1.0 instead of 6.0
if (iMax == bR) { // between yellow & magenta.
fH = (fG - fB) * ANGLE_TO_UNIT;
}
else if (iMax == bG) { // between cyan & yellow.
fH = (2.0f/6.0f) + ( fB - fR ) * ANGLE_TO_UNIT;
}
else { // between magenta & cyan.
fH = (4.0f/6.0f) + ( fR - fG ) * ANGLE_TO_UNIT;
}
// Wrap outlier Hues around the circle.
if (fH < 0.0f)
fH += 1.0f;
if (fH >= 1.0f)
fH -= 1.0f;
}
else {
// color is pure Black.
fS = 0;
fH = 0; // undefined hue
}
// Convert from floats to 8-bit integers
bH = (int)(0.5f + fH * 255.0f);
bS = (int)(0.5f + fS * 255.0f);
bV = (int)(0.5f + fV * 255.0f);
// Clip the values to make sure it fits within the 8bits
//if (bH > 255 || bH < 0 || bS > 255 || bS < 0 || bV > 255 || bV < 0) {
// cout << "Warning: HSV pixel(" << x << "," << y << ") is being clipped. " << bH << "," << bS << "," << bV << endl;
//}
if (bH > 255)
bH = 255;
if (bH < 0)
bH = 0;
if (bS > 255)
bS = 255;
if (bS < 0)
bS = 0;
if (bV > 255)
bV = 255;
if (bV < 0)
bV = 0;
}
// Create a HSV image from the RGB image using the full 8-bits, since OpenCV only allows Hues up to 180 instead of 255.
// ref: "http://cs.haifa.ac.il/hagit/courses/ist/Lectures/Demos/ColorApplet2/t_convert.html"
// Remember to free the generated HSV image.
IplImage* convertImageRGBtoHSV(const IplImage *imageRGB)
{
// Create a blank HSV image
IplImage *imageHSV = cvCreateImage(cvGetSize(imageRGB), 8, 3);
if (!imageHSV || imageRGB->depth != 8 || imageRGB->nChannels != 3) {
LOG("ERROR in convertImageRGBtoHSV()! Bad input image.\n");
exit(1);
}
int h = imageRGB->height; // Pixel height
int w = imageRGB->width; // Pixel width
int rowSizeRGB = imageRGB->widthStep; // Size of row in bytes, including extra padding
char *imRGB = imageRGB->imageData; // Pointer to the start of the image pixels.
int rowSizeHSV = imageHSV->widthStep; // Size of row in bytes, including extra padding
char *imHSV = imageHSV->imageData; // Pointer to the start of the image pixels.
for (int y=0; y<h; y++) {
for (int x=0; x<w; x++) {
// Get the RGB pixel components. NOTE that OpenCV stores RGB pixels in B,G,R order.
uchar *pRGB = (uchar*)(imRGB + y*rowSizeRGB + x*3);
int bB = *(uchar*)(pRGB+0); // Blue component
int bG = *(uchar*)(pRGB+1); // Green component
int bR = *(uchar*)(pRGB+2); // Red component
// Do the conversion.
int bH, bS, bV;
convertPixelRGBtoHSV_256(bR,bG,bB, bH,bS,bV);
// Set the HSV pixel components
uchar *pHSV = (uchar*)(imHSV + y*rowSizeHSV + x*3);
*(pHSV+0) = bH; // H component
*(pHSV+1) = bS; // S component
*(pHSV+2) = bV; // V component
}
}
return imageHSV;
}
// Do the color conversion of a single pixel, from HSV to RGB using Hue values between 0 to 255, whereas OpenCV only allows Hues up to 180 instead of 255.
// ref: "http://cs.haifa.ac.il/hagit/courses/ist/Lectures/Demos/ColorApplet2/t_convert.html"
inline void convertPixelHSVtoRGB_256(int bH, int bS, int bV, int &bR, int &bG, int &bB)
{
float fH, fS, fV;
float fR, fG, fB;
const float FLOAT_TO_BYTE = 255.0f;
const float BYTE_TO_FLOAT = 1.0f / FLOAT_TO_BYTE;
// Convert from 8-bit integers to floats
fH = (float)bH * BYTE_TO_FLOAT;
fS = (float)bS * BYTE_TO_FLOAT;
fV = (float)bV * BYTE_TO_FLOAT;
// Convert from HSV to RGB, using float ranges 0.0 to 1.0
int iI;
float fI, fF, p, q, t;
if( bS == 0 ) {
// achromatic (grey)
fR = fG = fB = fV;
}
else {
//if (bH < 0 || bH >= 255 || bS < 0 || bS > 255 || bV < 0 || bV > 255) {
// cout << "ERROR: HSVi pixel(" << x << "," << y << ") is being clipped. " << bH << "," << bS << "," << bV << endl;
// cout << "ERROR: HSVf pixel(" << x << "," << y << ") is being clipped. " << fH << "," << fS << "," << fV << endl;
//}
// If Hue == 1.0, then wrap it around the circle to 0.0
if (fH >= 1.0f)
fH = 0.0f;
fH *= 6.0; // sector 0 to 5