-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHelperFunctions.cpp
657 lines (542 loc) · 13.2 KB
/
HelperFunctions.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
// 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 <QImage>
#include <QJsonDocument>
#include "opencv2/opencv.hpp"
#include "opencv/highgui.h"
#include "mainwindow.h"
#include "globals.h"
#include "HelperFunctions.h"
using namespace std;
cv::Scalar HelperFunctions::QC2S(QColor color)
{
int r, g, b;
color.getRgb(&r, &g, &b);
return cv::Scalar(b, g, r); // swap RGB-->BGR
}
//scalar --> qcolor
QColor HelperFunctions::S2QC(cv::Scalar color)
{
return QColor(color[2], color[1], color[0]); // swap RGB-->BGR
}
cv::Mat HelperFunctions::convertFloatToGreyscaleMat(cv::Mat im)
{
cv::Mat sim, img;
vector<cv::Mat> channels;
cv::Mat g(cv::Size(im.rows, im.cols), CV_8UC1, cv::Scalar(0));
normalize(im, im, 0, 255, cv::NORM_MINMAX, CV_32F);
im.convertTo(img, CV_8UC1);
channels.push_back(img); //R
channels.push_back(img); //G
channels.push_back(img); //B
merge(channels, sim);
return sim;
}
QVector3D HelperFunctions::addPointToVector3D(QVector3D vect, QPointF pt)
{
QVector3D ret = vect;
ret.setX(vect.x() + pt.x());
ret.setY(vect.y() + pt.y());
return ret;
}
bool HelperFunctions::checkMatCompatibility(cv::Mat& in, cv::Mat& out, const int expectedType, bool checkType)
{
if (in.type() != out.type())
return false;
if (checkType)
{
if (in.type() != expectedType)
return false;
}
return true;
}
QSharedPointer<QRect> HelperFunctions::getPaddRect(QPoint ptStart, QPoint ptEnd, int levels)
{
// padd region to be divisible by 2
int width = abs(ptEnd.x() - ptStart.x());
int height = abs(ptEnd.y() - ptStart.y());
QPoint dims(width, height);
int newSizeW = HelperFunctions::padd(width, levels);
int newSizeH = HelperFunctions::padd(height, levels);
QPoint newSize(newSizeW, newSizeH);
QPoint start = ptStart;
QPoint end = ptEnd;
if (ptEnd.x() < ptStart.x() || ptEnd.y() < ptStart.y())
{
start = ptEnd;
end = ptStart;
}
QSize s(newSizeW, newSizeH);
return QSharedPointer<QRect>(new QRect(ptStart - (newSize - dims) / 2, s));
}
/**
*
* Returns a string representation of the opencv image type
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::type2str
* Qualifier
* @param int type
* @return std::string
* Access public
*/
QString HelperFunctions::type2str(int type)
{
QString r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch (depth) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans + '0');
return r;
}
// RLHistogram should be binary array where 0 is bar 1 is white
QString HelperFunctions::getBarcodeStringfromVector(int* vect, int& size)
{
// find out size of bar - by constructing histogram
int* hist = new int[size]; // sufficiently long to capture
// get pixel sizes of black bars
int length = 0;
for(int i=0;i<size;i++)
{
hist[i] = 0;
if (vect[i] > 0)
length++;
if (vect[i] == 0 && length > 0)
{
hist[length]++;
length = 0;
}
}
if(length>0)
hist[length]++;
int newSize = size;
int maxPeak = 0;
for (int i = 0; i < size; i++)
{
if(hist[i] > 0)
newSize = i;
maxPeak = MAX(maxPeak, hist[i]);
}
newSize+=1;
// find second biggest peak use this as threshold
for (int i = 0; i < newSize; i++)
{
if(hist[i] != maxPeak)
maxPeak = MAX(maxPeak, hist[i]);
}
int singleLine = -1;
for (int i = 0; i < newSize; i++)
{
if (hist[i] >= maxPeak)
{
singleLine = i;
break;
}
}
int lengthBlack = 0;
int lengthWhite = 0;
QString str;
for (int i = 0; i < size; i++)
{
if (vect[i] > 0) // black
lengthBlack++;
else
lengthWhite++;
if (vect[i] == 0 && lengthBlack > 0) // change to black
{
if (abs(lengthBlack - singleLine) < abs(lengthBlack - singleLine * 2))
str += "1";
else
str += "2";
lengthBlack = 0;
}
else if(vect[i] > 0 && lengthWhite>0) // change to white
{
if (abs(lengthWhite - singleLine) < abs(lengthWhite - singleLine * 2))
str += "_";
else
str += "__";
lengthWhite = 0;
}
}
if (lengthWhite > 0)
{
if (abs(lengthWhite - singleLine) < abs(lengthWhite - singleLine * 2))
str += "_";
else
str += "__";
lengthWhite = 0;
}
else if (lengthBlack > 0)
{
if (abs(lengthBlack - singleLine) < abs(lengthBlack - singleLine * 2))
str += "1";
else
str += "2";
lengthBlack = 0;
}
// now find single, double bars & spaces
return str;
}
QString HelperFunctions::toDataURL(cv::Mat image)
{
std::vector<uint8_t> buffer;
cv::imencode(".png", image, buffer);
QByteArray byteArray = QByteArray::fromRawData((const char*)buffer.data(), buffer.size());
QString base64Image(byteArray.toBase64());
return base64Image;
}
/**
*
* Returns an OpenCV image from a histogram (b_hist)
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::displayHistogram
* Qualifier
* @param int histSize
* @param cv::Mat b_hist
* @param int hist_w
* @param int hist_h
* @return cv::Mat
* Access public
*/
cv::Mat HelperFunctions::displayHistogram(cv::Mat b_hist, int histSize, int hist_w, int hist_h)
{
// Draw the histograms for B, G and R
int fontFace = cv::FONT_HERSHEY_TRIPLEX;
int fontScale = 1, thickness=1;
cv::Scalar red(255, 0, 0);
cv::Scalar green(0, 255, 0);
cv::Scalar blue(0, 0, 255);
int maxheight = 0;
cv::String text;
cv::Size textSize;
int baseline = 0;
// create image for histogram
cv::Mat histImage(hist_h, hist_w, CV_8UC3, cv::Scalar(0, 0, 0));
// bin size in image
double bin_w = (((double)hist_w) / ((double)histSize));
std::vector<cv::Point> lines;
try
{
/// Draw for each channel
for (int i = 0; i < histSize; i+=50)
{
text = cv::format("%d", i);
textSize = cv::getTextSize(text, fontFace, fontScale, 1, &baseline);
maxheight = max(maxheight, textSize.height);
putText(histImage, text, cv::Point((int)(bin_w*i), hist_h), fontFace, fontScale, red, 8, true);
}
maxheight *= 1.5;
// Normalize the result to [ 0, histImage.rows ] - i.e. fit in screen
normalize(b_hist, b_hist, 0, histImage.rows - maxheight, cv::NORM_MINMAX);
/// Draw for each channel
for (int i = 0; i < histSize; i++)
{
lines.push_back(cv::Point((int)(bin_w*i), hist_h - maxheight - cvRound(b_hist.at<float>(i))));
}
const cv::Point *pts = (const cv::Point*) cv::Mat(lines).data;
int npts = cv::Mat(lines).rows;
polylines(histImage, &pts, &npts, 1,
false, // draw closed contour (i.e. joint end to start)
cv::Scalar(0, 255, 0), // colour RGB ordering (here = green)
1, // line thickness
CV_AA, 0);
}
catch (cv::Exception& e)
{
const char* err_msg = e.what();
DBOUT("exception caught: " << err_msg << std::endl);
}
return histImage;
}
void HelperFunctions::rotate90(cv::Mat &matImage, RotateFlags::RotateFlags rotflag)
{
//1=CW, 2=CCW, 3=180
if (rotflag == RotateFlags::ROTATE_90_CLOCKWISE) {
transpose(matImage, matImage);
flip(matImage, matImage, 1); //transpose+flip(1)=CW
}
else if (rotflag == RotateFlags::ROTATE_180) {
transpose(matImage, matImage);
flip(matImage, matImage, 0); //transpose+flip(0)=CCW
}
else if (rotflag == RotateFlags::ROTATE_90_COUNTERCLOCKWISE) {
flip(matImage, matImage, -1); //flip(-1)=180
}
else
{
// ROTATE_90_CLOCKWISE
transpose(matImage, matImage);
flip(matImage, matImage, 1); //transpose+flip(1)=CW
}
}
/**
*
* Resizes image while preserving aspect ratio
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::resizeImagePreserve
* Qualifier
* @param cv::Mat & imageIn
* @param cv::Mat & imageOut
* @param int newWidth
* @param int newHeight
* @return void
* Access public
*/
void HelperFunctions::resizeImagePreserve(cv::Mat &imageIn, cv::Mat &imageOut, int newWidth, int newHeight)
{
int w = newWidth;
int h = newHeight;
double ratio = ((double)imageIn.cols) / ((double)imageIn.rows); // width/height
int scaledH = (int)round(((double)w) / ratio);
int scaledW = (int)round(((double)h)*ratio);
if (scaledH > h) { w = scaledW; }
else { h = scaledH; }
cv::resize(imageIn, imageOut, cv::Size(w, h), 0, 0, cv::INTER_LINEAR);
}
/**
*
* make QImage from OpenCV image
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::makeQImage
* Qualifier
* @param cv::Mat im
* @param bool bRGBSwap
* @return QT_NAMESPACE::QImage
* Access public
*/
QImage HelperFunctions::makeQImage(cv::Mat im, bool bRGBSwap)
{
QImage::Format form = getFormat(im.type());
QImage pImage = QImage(im.data, im.cols, im.rows, (int)im.step, form);
if (bRGBSwap)
pImage.rgbSwapped();
return pImage;
}
/**
*
* Returns QT Image type for OpenCV type
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::getFormat
* Qualifier
* @param int type
* @return QT_NAMESPACE::QImage::Format
* Access public
*/
QImage::Format HelperFunctions::getFormat(int type)
{
#ifdef DEBUGPRINT
qDebug() << "Function Name: " << Q_FUNC_INFO;
#endif
switch (type) {
case CV_8UC3: {
return QImage::Format_RGB888;
}
case CV_8U: {
return QImage::Format_Indexed8;
}
case CV_8UC4: {
return QImage::Format_ARGB32;
}
return QImage::Format_Invalid;
}
return QImage::Format_Invalid;
}
QJsonObject HelperFunctions::ObjectFromString(const QString& in)
{
QJsonObject obj;
QJsonDocument doc = QJsonDocument::fromJson(in.toUtf8());
// check validity of the document
if (!doc.isNull())
{
if (doc.isObject())
{
obj = doc.object();
}
}
return obj;
}
/**
*
* determines if image is greyscale
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::isGrayImage
* Qualifier // returns true if the given 3 channel image is B = G = R
* @param cv::Mat img
* @return bool
* Access public
*/
bool HelperFunctions::isGrayImage(const cv::Mat& img) // returns true if the given 3 channel image is B = G = R
{
for (int j = 0; j < img.rows; j++)
{
for (int i = 0; i < img.cols; i++)
{
if (img.ptr<uchar>(j)[(i * 3)] != img.ptr<uchar>(j)[(i * 3) + 1] ||
(img.ptr<uchar>(j)[(i * 3)] != img.ptr<uchar>(j)[(i * 3) + 2]))
return false;
}
}
return true;
}
bool HelperFunctions::pointInEllipse(QRectF ellipseRect, QPointF pt)
{
bool inObject = false;
double rx = ellipseRect.width() / 2.0;
double ry = ellipseRect.height() / 2.0;
double rx2 = rx*rx;
double ry2 = ry*ry;
double dx = pt.x() - ellipseRect.center().x();
double dx2 = dx*dx;
double dy = pt.y() - ellipseRect.center().y();
double dy2 = dy*dy;
if(ellipseRect.contains(pt))
{
// within rectangle at least
return dx2 / rx2 + dy2 / ry2 <= 1;
}
return false;
}
bool HelperFunctions::pointInPoly(QPolygonF poly, QPointF pt)
{
int i, j;
bool inObject = false;
int nvert = poly.size();
bool c = false;
for (i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((poly.at(i).y() >= pt.y()) != (poly.at(j).y() >= pt.y())) &&
(pt.x() <= (poly.at(j).y() - poly.at(i).x()) * (pt.y() - poly.at(i).y()) / (poly.at(j).y() - poly.at(i).y()) + poly.at(i).x()))
c = !c;
}
return c;
}
int* HelperFunctions::getCImage(const cv::Mat& img) // returns true if the given 3 channel image is B = G = R
{
int* im = new int[img.rows*img.cols];
for (int j = 0; j < img.rows; j++)
{
for (int i = 0; i < img.cols; i++)
{
cv::Vec3b val = img.at<cv::Vec3b>(j, i);
im[i + j*img.cols] = (int)val[0] * 0.114 + val[1] * 0.587 + val[2] * 0.299;
}
}
return im;
}
/**
*
* Handles vector boundaries by reflecting values
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::reflect
* Qualifier
* @param int M
* @param int x
* @return int
* Access public
*/
int HelperFunctions::reflect(int M, int x)
{
if (x < 0)
{
return -x - 1;
}
if (x >= M)
{
return 2 * M - x - 1;
}
return x;
}
/**
*
* returns a 0-255 scaled opencv image
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::putMatScale
* Qualifier
* @param cv::Mat im
* @param bool scale
* @param bool bRed
* @return cv::Mat
* Access public
*/
cv::Mat HelperFunctions::putMatScale(cv::Mat im, bool scale, bool bRed)
{
cv::Mat cMat;
cv::normalize(im, cMat, 255, 0);
return cMat;
}
cv::Mat HelperFunctions::testReturn(cv::Mat& im)
{
cv::Mat cMat = cv::Mat(im.rows, im.cols, CV_8UC3, cv::Scalar(0));
for (int j = 0; j < im.rows; j++)
{
for (int i = 0; i < im.cols; i++)
{
cMat.ptr<uchar>(j)[(i * 3)] = 0;
cMat.ptr<uchar>(j)[(i * 3) + 1] = j % 255;
cMat.ptr<uchar>(j)[(i * 3) + 2] = i % 255;
}
}
return cMat;
}
/**
*
* prints 2D matrix to screen
*
* @author David Watts
* @since 2017/03/07
*
* FullName HelperFunctions::DebugPrintMat
* Qualifier
* @param cv::Mat mat
* @return void
* Access public
*/
void HelperFunctions::DebugPrintMat(cv::Mat mat)
{
for (int i = 0; i < mat.cols; i++)
{
for (int j = 0; j < mat.rows; j++)
{
std::cout << (int)mat.at<uchar>(j, i) << " ";
}
}
}