-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdatamatrixreader.cpp
More file actions
1417 lines (1146 loc) · 52.7 KB
/
datamatrixreader.cpp
File metadata and controls
1417 lines (1146 loc) · 52.7 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
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
#include "datamatrixreader.h"
#include <QDebug>
#include <QApplication>
#include <QDir>
#include <QDateTime>
#include <QThread>
#include <houghresultdata.h>
#include <cv.h>
#include <highgui.h>
#include <QProcess>
#include <QTextEdit>
#include <QTemporaryFile>
#include <QTextStream>
#include <QFile>
#include <iplimageconverter.h>
/*
* Konstruktor.
*/
DataMatrixReader::DataMatrixReader()
{
this->saveImageStatus = false;
this->allRunsPath = QDir::tempPath() + "/DataMatrixReaderRuns";
QDir allRunsPath = QDir(this->allRunsPath);
if (!allRunsPath.exists(this->allRunsPath))
{
allRunsPath.mkpath(this->allRunsPath);
}
}
/*
* Dekonstruktor.
*/
DataMatrixReader::~DataMatrixReader()
{
delete this->dmtxProcess;
delete this->dmtxReadInputImage;
delete this->dmtxReadOutputFile;
}
/*
* Löscht alle zwischenzeitlich gespeicherten Dateien aller Läufe.
*/
void DataMatrixReader::clearAllRuns()
{
QDir allRunsPath = QDir(this->allRunsPath);
if (allRunsPath.exists(this->allRunsPath))
{
QFileInfoList dirs = allRunsPath.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs);
foreach (QFileInfo dir, dirs)
{
QDir currentDir = QDir(dir.absoluteFilePath());
QFileInfoList files = currentDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);
foreach (QFileInfo currentFile, files)
{
currentDir.remove(currentFile.fileName());
}
currentDir.rmdir(dir.absoluteFilePath());
}
}
}
/*
* Ermittelt die Anzahl der vorherigen Läufe.
*/
int DataMatrixReader::getPreviousRunCount()
{
int runCount = 0;
QDir allRunsPath = QDir(this->allRunsPath);
if (allRunsPath.exists(this->allRunsPath))
{
QFileInfoList dirs = allRunsPath.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs);
runCount = dirs.count();
}
return runCount;
}
/*
* Erstellt den Pfad zum Speicherort eines bestimmten Laufs.
*/
QString DataMatrixReader::createRunPath(QString filePath)
{
QFileInfo fileInfo = QFileInfo(filePath);
QString dateTime = QDateTime::currentDateTime().toString("dd.MM.yyyy hh.mm.ss");
QString path = this->allRunsPath + "/" + fileInfo.fileName() + " " + dateTime;
QDir runPath = QDir(path);
if (!runPath.exists(path))
{
runPath.mkpath(path);
}
return runPath.absolutePath();
}
/*
* Haupteinsprungspunkt für den DataMatrixReader.
* Hier beginnt die Analyse eines Bildes.
*/
void DataMatrixReader::processImage(QString fileName)
{
this->saveImageCount = 0;
// Sollen die Bilder gespeichert werden, wird ein spezieller Pfad dafür erstellt.
if (this->saveImageStatus)
{
this->runPath = this->createRunPath(fileName);
}
// Das Quellbild in Farbe laden und daraus ein zusätzliches Graubild erstellen.
IplImage* sourceColorImage = this->loadSourceImage(fileName);
IplImage* sourceGrayImage = this->createGrayImage(sourceColorImage);
QStringList sourceGrayImageData;
this->saveAndSendImage(sourceGrayImage, "SourceGrayImage.jpg", "Source image (gray)",
sourceGrayImageData);
// Geradenerkennung mittels Hough-Transformation im Graubild.
HoughResultData *houghResultData = this->processHough(sourceGrayImage);
CvPoint* dataMatrixEdges = houghResultData->getDataMatrixEdges();
IplImage* currentWorkColorImage = sourceColorImage;
// Muss das aktuelle Bild gedreht werden, um die Eckpunkte besser erkennen zu können?
if (houghResultData->getHasToBeRotated())
{
double angle = 60;
// Das Bild drehen, damit die Eckpunkte sicher gefunden werden können.
IplImage* rotatedColorImage = this->rotateImage(sourceColorImage, houghResultData->getCenter(),
angle);
QStringList colorImageData;
colorImageData.append("Rotation center: " + this->cvPointToString(houghResultData->getCenter()));
colorImageData.append("Rotation angle: " + QString::number(angle) + " degree");
this->saveAndSendImage(rotatedColorImage, "RotatedImage.jpg", "Rotated image", colorImageData);
// Nach dem Drehen können die Eckpunkte neu berechnet werden.
dataMatrixEdges = this->calculateEdgesAfterRotation(houghResultData, sourceGrayImage,
sourceColorImage, rotatedColorImage, angle);
currentWorkColorImage = rotatedColorImage;
}
IplImage* currentWorkThreshImage = this->processThresh(currentWorkColorImage,
"CurrentWorkThreshImage.jpg",
"Current work image with threshold");
// Die Position (welche Ecke der DataMatrix) des Finder-Punktes ermitteln.
int finderPos = this->detectFinderPosition(dataMatrixEdges, currentWorkThreshImage);
CvPoint finder = dataMatrixEdges[finderPos];
CvPoint max2 = dataMatrixEdges[(finderPos + 2) % 4];
CvPoint max1 = this->detectSecondMaxPoint(houghResultData->getHoughLines(), max2, finder);
CvPoint center = this->calculateCenterPoint(houghResultData->getDataMatrixEdges());
this->paintCurrentPositions(currentWorkThreshImage, max1, max2, center,
finder, dataMatrixEdges[(finderPos + 1) % 4]);
double angle = this->calculateRotationAngle(dataMatrixEdges, finderPos);
IplImage* currentWorkRotatedImage = this->rotateImage(currentWorkThreshImage, center, angle);
// Nach dem Rotieren müssten auch alle Punkte gedreht werden, die noch Verwendet werden.
this->rotateDataMatrixEdges(dataMatrixEdges, center, angle);
max1 = this->rotatePoint(center, max1, angle);
finder = this->rotatePoint(center, finder, angle);
this->calculateMissingPoint(dataMatrixEdges, finderPos, max1);
this->paintDataMatrixEdges(currentWorkRotatedImage, dataMatrixEdges, finder);
IplImage* currentWorkImage = this->removePerspective(currentWorkRotatedImage, dataMatrixEdges, finderPos);
IplImage* currentROIImage = this->createROI(currentWorkImage, dataMatrixEdges, finderPos);
IplImage* threshedROIImage = this->processThresh(currentROIImage,
"ThreshedROIImage.jpg",
"ROI image with binary threshold.");
IplImage* currentSmoothedImage = this->smoothImage(threshedROIImage);
this->processDataBlock(currentSmoothedImage);
}
/*
* Läd das Quellbild für die Analyse.
*/
IplImage* DataMatrixReader::loadSourceImage(QString fileName)
{
QByteArray bytes = fileName.toAscii();
const char * ptrSourceColorImage = bytes.data();
IplImage* sourceColorImage = cvLoadImage(ptrSourceColorImage, 1); // Als Farbbild laden
QStringList sourceColorImageData;
this->saveAndSendImage(sourceColorImage, "SourceColorImage.jpg", "Source image (color)",
sourceColorImageData);
return sourceColorImage;
}
/*
* Wandelt das übergebene Farbild ein ein Graubild um.
*/
IplImage* DataMatrixReader::createGrayImage(IplImage* sourceImage)
{
IplImage* sourceGrayImage = cvCreateImage(cvGetSize(sourceImage), IPL_DEPTH_8U, 1); // 8 Bit, 1 Farbe
cvCvtColor(sourceImage, sourceGrayImage, CV_BGR2GRAY); // in Graubild konvertieren
return sourceGrayImage;
}
/*
* Wendet auf das übergebene Bild die Hough-Transformation an.
*/
HoughResultData* DataMatrixReader::processHough(IplImage *sourceGrayImage)
{
IplImage* cannyResultImage = this->processCanny(sourceGrayImage);
/*-----------------------------------------------------------------------------
* Die Hough- Transformation detektiert alle Geraden in dem Bild, die durch
* zwei Punkte beschrieben werden. Dabei wird der Winkel, in dem diese
* Geraden zum Ursprung liegen können in 0.5° Schritten (2*PI/720) durchgegangen.
* Dieser hohe Wert bedeutet eine hohe Rechenintensitaet.
*-----------------------------------------------------------------------------*/
CvSeq* lines = cvHoughLines2(cannyResultImage,
cvCreateMemStorage(0),
CV_HOUGH_PROBABILISTIC, 1, CV_PI/720, 35, 100, 250);
HoughResultData *houghResultData = this->processHoughResult(lines,
cannyResultImage->width,
cannyResultImage->height);
houghResultData->setHoughLines(lines);
this->paintHoughLines(sourceGrayImage, houghResultData);
return houghResultData;
}
/*
* Berechnet die Ecken der DataMatrix nach dem Drehen des Bildes erneut.
*/
CvPoint* DataMatrixReader::calculateEdgesAfterRotation(HoughResultData *houghResultData, IplImage* sourceGrayImage, IplImage* sourceColorImage, IplImage* rotatedColorImage, double angle)
{
int x_max = 0;
int y_max = 0;
int x_min = sourceGrayImage->width;
int y_min = sourceGrayImage->height;
CvPoint *edge = new CvPoint[4];
IplImage* rotatedHoughColorImageShowResult = cvCreateImage( cvGetSize(sourceColorImage), 8, 3 );
rotatedHoughColorImageShowResult = cvCloneImage(rotatedColorImage);
for( int i = 0; i < houghResultData->getHoughLines()->total; i++ )
{
CvPoint* line = (CvPoint*)cvGetSeqElem(houghResultData->getHoughLines(),i);
int x_p0 = *(&line[0].x);
int y_p0 = *(&line[0].y);
int x_p1 = *(&line[1].x);
int y_p1 = *(&line[1].y);
CvPoint p0 = this->rotatePoint(houghResultData->getCenter(),
this->setCvPoint(x_p0, y_p0),
angle);
CvPoint p1 = this->rotatePoint(houghResultData->getCenter(),
this->setCvPoint(x_p1, y_p1),
angle);
x_p0 = p0.x;
y_p0 = p0.y;
x_p1 = p1.x;
y_p1 = p1.y;
*(&line[0].x) = x_p0;
*(&line[0].y) = y_p0;
*(&line[1].x) = x_p1;
*(&line[1].y) = y_p1;
cvLine(rotatedHoughColorImageShowResult, p0, p1, cvScalar(255, 0, 0));
/*-----------------------------------------------------------------------------
* Berechnen der Eckpunkte der Matrix. Liegen Kanten der Matrix senkrecht oder
* waagerecht zum Koordinatenkreuz, so ist eine eindeutige Bestimmung im ersten
* Durchlauf noch nicht möglich. Die Matrix wird in diesem Fall um 60° gedreht.
*-----------------------------------------------------------------------------*/
x_max = max(x_max, max(x_p0, x_p1));
if( x_max == x_p0)
edge[1] = setCvPoint( x_p0, y_p0);
if( x_max == x_p1)
edge[1] = setCvPoint( x_p1, y_p1);
x_min = min(x_min, min(x_p0, x_p1));
if( x_min == x_p0)
edge[3] = setCvPoint( x_p0, y_p0);
if( x_min == x_p1)
edge[3] = setCvPoint( x_p1, y_p1);
y_max = max(y_max, max(y_p0, y_p1));
if( y_max == y_p0)
edge[2] = setCvPoint( x_p0, y_p0);
if( y_max == y_p1)
edge[2] = setCvPoint( x_p1, y_p1);
y_min = min(y_min, min(y_p0, y_p1));
if( y_min == y_p0)
edge[0] = setCvPoint( x_p0, y_p0);
if( y_min == y_p1)
edge[0] = setCvPoint( x_p1, y_p1);
}
QStringList houghColorImageData;
this->saveAndSendImage(rotatedHoughColorImageShowResult, "RotatedHoughColorImageShowResult.jpg",
"Rotated Hough result image", houghColorImageData);
return edge;
}
/*
* Versucht im übergebenen Bild den DataMatrix Datenblock zu finden,
* die Spalten- und Zeilenanzahl zu bestimmen und aus dem Datenblock
* eine Bit-Matrix zu erstellen.
*/
void DataMatrixReader::processDataBlock(IplImage* currentImage)
{
int offset = 4;
CvPoint topLeft = this->setCvPoint(offset, offset);
CvPoint topRight = this->setCvPoint(currentImage->width - offset, offset);
CvPoint bottomRight = this->setCvPoint(currentImage->width - offset, currentImage->height - offset);
BlockData blockDataTop = this->calculateAvgBlockSize(currentImage, topLeft, topRight);
BlockData blockDataRight = this->calculateAvgBlockSize(currentImage, bottomRight, topRight);
IplImage* imageBlockLines = cvCreateImage(cvGetSize(currentImage), IPL_DEPTH_8U, 3);
cvCvtColor(currentImage, imageBlockLines, CV_GRAY2BGR);
IplImage* imageTrueFields = cvCreateImage(cvGetSize(currentImage), IPL_DEPTH_8U, 3);
cvCvtColor(currentImage, imageTrueFields, CV_GRAY2BGR);
cvLine(imageBlockLines, topLeft, topRight, cvScalar(0, 0, 255));
cvLine(imageBlockLines, bottomRight, topRight, cvScalar(0, 255, 0));
double cvPointX = 0;
double cvPointY = 0;
bool** fieldValues = new bool*[blockDataTop.getBlockCount()];
int trueFieldCount = 0;
int falseFieldCount = 0;
for (int i = 0; i < blockDataTop.getBlockCount(); i++)
{
fieldValues[i] = new bool[blockDataTop.getBlockCount()];
}
for (int x = 0; x < blockDataTop.getBlockCount(); x++)
{
for (int y = 0; y < blockDataRight.getBlockCount(); y++)
{
CvPoint center = this->setCvPoint(0, 0);
cvPointX = topLeft.x
+ blockDataTop.getLineStart()
+ (blockDataTop.getAvgBlockSize() / 2)
+ x * blockDataTop.getAvgBlockSize();
center.x = cvPointX;
cvPointY = bottomRight.y + 1
- blockDataRight.getLineStart()
- (blockDataRight.getAvgBlockSize() / 2)
- y * blockDataRight.getAvgBlockSize();
center.y = cvPointY;
CvScalar pixelValue = cvGet2D(currentImage, center.y, center.x);
fieldValues[x][y] = pixelValue.val[0] == 0;
cvLine(imageBlockLines, this->setCvPoint(center.x - 2, center.y),
this->setCvPoint(center.x + 2, center.y), cvScalar(0, 0, 255));
cvLine(imageBlockLines, this->setCvPoint(center.x, center.y - 2),
this->setCvPoint(center.x, center.y + 2), cvScalar(0, 0, 255));
if (pixelValue.val[0] == 0)
{
cvLine(imageTrueFields, this->setCvPoint(center.x - 2, center.y),
this->setCvPoint(center.x + 2, center.y), cvScalar(0, 0, 255));
cvLine(imageTrueFields, this->setCvPoint(center.x, center.y - 2),
this->setCvPoint(center.x, center.y + 2), cvScalar(0, 0, 255));
trueFieldCount++;
}
else
{
falseFieldCount++;
}
}
}
QStringList imageBlockLinesData;
imageBlockLinesData.append("Horizontal & vertical block count: "
+ QString::number(blockDataRight.getBlockCount()));
this->saveAndSendImage(imageBlockLines, "ImageBlockLines.jpg", "Image with block lines.",
imageBlockLinesData);
QStringList imageTrueFieldsData;
imageTrueFieldsData.append("True field count: " + QString::number(trueFieldCount));
imageTrueFieldsData.append("False field count: " + QString::number(falseFieldCount));
this->saveAndSendImage(imageTrueFields, "ImageTrueFields.jpg", "Image with true field values.",
imageTrueFieldsData);
this->drawNewMatrix(blockDataTop.getBlockCount(), fieldValues);
}
/*
* Erstellt aus der übergebenen Bit-Matrix ein neues Bild mit einer neu gezeichneten Matrix.
*/
void DataMatrixReader::drawNewMatrix(int blockCount, bool **fieldValues)
{
int blockSize = 10;
int offset = 5;
int width = (blockSize * (blockCount + 2)) + offset * 2;
int height = width;
// Neues Bild erstellen und alle Pixel auf weiß setzen.
IplImage *newMatrixImage = cvCreateImage(cvSize(width, height), 8, 1);
cvAddS(newMatrixImage, cvScalar(255, 255, 255), newMatrixImage);
// Datenbereich der DataMatrix.
for (int x = 1; x <= blockCount; x++)
{
for (int y = 1; y <= blockCount; y++)
{
CvPoint bottomLeft;
bottomLeft.x = x * blockSize + offset;
bottomLeft.y = newMatrixImage->height - blockSize * y - offset;
CvPoint topRight;
topRight.x = bottomLeft.x + blockSize - 1;
topRight.y = bottomLeft.y - blockSize + 1;
if (fieldValues[x - 1][y - 1])
{
cvRectangle(newMatrixImage, bottomLeft, topRight, cvScalar(0, 0, 0), CV_FILLED);
}
}
}
for (int x = 0; x < blockCount + 2; x++)
{
// Untere Seite des Finder-Patterns.
CvPoint bottomLeft;
bottomLeft.x = x * blockSize + offset;
bottomLeft.y = newMatrixImage->height - offset;
CvPoint topRight;
topRight.x = bottomLeft.x + blockSize - 1;
topRight.y = bottomLeft.y - blockSize + 1;
cvRectangle(newMatrixImage, bottomLeft, topRight, cvScalar(0, 0, 0), CV_FILLED);
// Linke Seite des Finder-Patterns.
bottomLeft.x = offset;
bottomLeft.y = newMatrixImage->height - (x * blockSize) - offset;
topRight.x = bottomLeft.x + blockSize - 1;
topRight.y = bottomLeft.y - blockSize + 1;
cvRectangle(newMatrixImage, bottomLeft, topRight, cvScalar(0, 0, 0), CV_FILLED);
if (x % 2 == 0)
{
// Oberes alternating-Pattern.
bottomLeft.x = x * blockSize + offset;
bottomLeft.y = blockSize + offset;
topRight.x = bottomLeft.x + blockSize - 1;
topRight.y = bottomLeft.y - blockSize + 1;
cvRectangle(newMatrixImage, bottomLeft, topRight, cvScalar(0, 0, 0), CV_FILLED);
// Unteres alternating-Pattern.
bottomLeft.x = newMatrixImage->width - blockSize - offset;
bottomLeft.y = newMatrixImage->height - (x * blockSize) - offset;
topRight.x = bottomLeft.x + blockSize - 1;
topRight.y = bottomLeft.y - blockSize + 1;
cvRectangle(newMatrixImage, bottomLeft, topRight, cvScalar(0, 0, 0), CV_FILLED);
}
}
QStringList newMatrixImageData;
this->saveAndSendImage(newMatrixImage, "NewMatrix.jpg", "Our new created matrix.",
newMatrixImageData);
this->decodeDataMatrixBlock(newMatrixImage);
emit imageProcessed();
}
/*
* Versucht das übergebene Bild an das Programm "dmtxread" zu übergeben,
* um die darin kodierten Daten zu erhalten.
*/
void DataMatrixReader::decodeDataMatrixBlock(IplImage* newMatrixImage)
{
this->dmtxReadInputImage = new QTemporaryFile(QString(QDir::tempPath() + "/inputImage_XXXXXX.jpg"));
this->dmtxReadOutputFile = new QTemporaryFile();
if (this->dmtxReadInputImage->open() && this->dmtxReadOutputFile->open()) {
this->saveImage(dmtxReadInputImage->fileName(), newMatrixImage);
this->dmtxProcess = new QProcess(this);
QString dmtxReadPath = QApplication::applicationDirPath() + "/dmtxread/dmtxread.exe";
QStringList arguments;
arguments.append(this->dmtxReadInputImage->fileName());
this->dmtxProcess->setStandardOutputFile(this->dmtxReadOutputFile->fileName());
this->dmtxProcess->start(dmtxReadPath, arguments);
if (this->dmtxProcess->waitForFinished(3000))
{
QString decodedData;
if (this->dmtxProcess->exitCode() == 0
&& this->dmtxProcess->exitStatus() == 0
&& this->dmtxReadOutputFile->isReadable())
{
this->dmtxReadOutputFile->seek(0);
decodedData = QString(this->dmtxReadOutputFile->readAll());
QByteArray bytes = decodedData.toAscii();
const char * ptrDecodedData = bytes.data();
int width = 650, height = 650;
IplImage *decodedDataImage = cvCreateImage(cvSize(width, height), 8, 1);
cvAddS(decodedDataImage, cvScalar(255, 255, 255), decodedDataImage);
CvFont font;
CvSize text_size;
int ymin = 0;
CvPoint ptR;
cvInitFont(&font, CV_FONT_VECTOR0, 0.5, 0.5, 0.0, 2);
cvGetTextSize(ptrDecodedData, &font, &text_size, &ymin);
ptR.x = (width - text_size.width) / 2;
ptR.y = (height + text_size.height) / 2;
cvPutText(decodedDataImage, ptrDecodedData, ptR, &font, CV_RGB(0, 0, 0));
QStringList decodedDataImageData;
this->saveAndSendImage(decodedDataImage, "DecodedDataImage.jpg", "The decoded data!",
decodedDataImageData);
}
this->dmtxProcess->closeReadChannel(QProcess::StandardOutput);
this->dmtxProcess->closeWriteChannel();
this->dmtxProcess->close();
this->dmtxReadInputImage->close();
this->dmtxReadOutputFile->close();
this->dmtxReadInputImage->remove(this->dmtxReadInputImage->fileName());
this->dmtxReadOutputFile->remove(this->dmtxReadOutputFile->fileName());
}
}
}
/*
* Dreht die übergebenen Punkte im Array um den center und um den angegebenen Winkel.
*/
void DataMatrixReader::rotateDataMatrixEdges(CvPoint* dataMatrixEdges, CvPoint center, double angle)
{
/*-----------------------------------------------------------------------------
* Auch die gefundenen Punkte der DataMatrix müssen um den entspechenden Winkel
* gedreht werden.
*-----------------------------------------------------------------------------*/
for(int i = 0 ; i < 4 ; i++)
{
dataMatrixEdges[i] = rotatePoint( center, dataMatrixEdges[i], angle );
}
}
/*
* Berechnet die durchschnittliche Blockbreite des DataMatrix Datenblocks.
*/
BlockData DataMatrixReader::calculateAvgBlockSize(IplImage* currentImage, CvPoint startPoint, CvPoint endPoint)
{
double avgBlockSize = 0;
int max_buffer;
CvLineIterator iterator;
int previousPixel = 0;
int currentPixel = 0;
int blackCount = 0;
int whiteCount = 0;
int lineStart = 0;
int lineEnd = 0;
int lineLength = 0;
max_buffer = cvInitLineIterator(currentImage, startPoint, endPoint, &iterator, 8, 0);
previousPixel = iterator.ptr[0];
CV_NEXT_LINE_POINT(iterator);
for(int i = 1 ; i < max_buffer; i++)
{
currentPixel = iterator.ptr[0];
if (previousPixel == 255 && currentPixel == 0)
{
blackCount++;
}
else if (previousPixel == 0 && currentPixel == 255)
{
if (whiteCount == 0)
{
lineStart = i;
}
lineEnd = i;
whiteCount++;
}
previousPixel = currentPixel;
CV_NEXT_LINE_POINT(iterator);
}
whiteCount -= 1;
lineLength = lineEnd - lineStart;
avgBlockSize = (double)((double)lineLength / (whiteCount + blackCount));
return BlockData(avgBlockSize, whiteCount + blackCount, lineStart);
}
/*
* Wendet auf das übergebene Bild einen binären Threshold an.
*/
IplImage* DataMatrixReader::processThresh(IplImage *currentImage, QString fileName, QString description)
{
int threshold = 100;
int maxValue = 255;
int threshType = CV_THRESH_BINARY;
// Der Thresh muss auf einem Graubild arbeiten. Wird ein Farbild übergeben,
// muss es zuvor konvertiert werden.
IplImage* currentWorkGrayImage;
if (currentImage->nChannels == 3)
currentWorkGrayImage = this->createGrayImage(currentImage);
else
currentWorkGrayImage = currentImage;
IplImage* currentWorkThreshImage = cvCreateImage(cvGetSize(currentWorkGrayImage), IPL_DEPTH_8U, 1);
cvThreshold(currentWorkGrayImage, currentWorkThreshImage, threshold, maxValue, threshType);
QStringList threshImageData;
threshImageData.append("Threshold value: " + QString::number(threshold));
threshImageData.append("Threshold max value: " + QString::number(maxValue));
threshImageData.append("Threshold type: CV_THRESH_BINARY");
this->saveAndSendImage(currentWorkThreshImage, fileName, description, threshImageData);
return currentWorkThreshImage;
}
/*
* Entfernt kleine Bildstörungen durch eine Dialatation, gefolgt von einer Erosion.
*/
IplImage* DataMatrixReader::smoothImage(IplImage* currentImage)
{
IplImage* currentWorkImage = cvCreateImage(cvGetSize(currentImage),
currentImage->depth, currentImage->nChannels);
cvDilate(currentImage, currentWorkImage);
cvErode(currentWorkImage, currentWorkImage);
QStringList currentWorkImageData;
this->saveAndSendImage(currentWorkImage, "SmoothedImage.jpg",
"Current smoothed (Median) work image.", currentWorkImageData);
return currentWorkImage;
}
/*
* Hilfsmethode, um den Status zu verändern, ob die Bilder der Zwischenergebnisse
* im Dateisystem abgespeichert werden sollen.
*/
void DataMatrixReader::setSaveImagesStatus(bool saveImages)
{
this->saveImageStatus = saveImages;
}
/*
* Speichert das übergebene Bild bei Bedarf ab und schickt ein Signal,
* dass ein weiteres Bild zum Anzeigen in der Oberfläche vorhanden ist.
*/
void DataMatrixReader::saveAndSendImage(IplImage* currentImage, QString imageName, QString description, QStringList additionalData)
{
// Interessante Werte als zusätzliche Information anzeigen.
// In umgekehrter Reihenfolge am Anfang einfügen, damit sie in der GUI in der korrekten
// Reihenfolge angezeigt werden.
additionalData.insert(0, "OpenCV color-model: " + QString(currentImage->colorModel));
additionalData.insert(0, "Color-channels: " + QString::number(currentImage->nChannels));
additionalData.insert(0, "Depth: " + QString::number(currentImage->depth));
additionalData.insert(0, "Image-width/height: (" + QString::number(currentImage->width) + "x"
+ QString::number(currentImage->height) + ")");
// Wenn die Bilder zusätzlich noch im Dateisystem gespeichert werden sollen.
if (this->saveImageStatus)
{
this->saveImageCount++;
QString currentImagePath = this->runPath + "/" + QString::number(this->saveImageCount)
+ ". " + imageName;
this->saveImage(currentImagePath, currentImage);
}
// Das openCV IplImage-Format in das Qt QImage-Format konvertieren.
QImage &image = *IplImageConverter::IplImage2QImage(currentImage);
QPixmap pixmap = QPixmap::fromImage(image);
// Die "Außenwelt" über ein neues Bild benachrichtigen.
emit stepProcessed(StepData(imageName, description, QIcon(pixmap), pixmap, additionalData));
}
/*
* Berechnet den Mittelpunkt von den im Array übergebenen Punkten.
*/
CvPoint DataMatrixReader::calculateCenterPoint(CvPoint* dataMatrixEdges)
{
int x = 0;
int y = 0;
for (int i = 0; i < 4; i++)
{
x += dataMatrixEdges[i].x;
y += dataMatrixEdges[i].y;
}
CvPoint center = this->setCvPoint(x / 4, y / 4);
return center;
}
/*
* Wendet auf das übergebene Bild den Canny-Edge-Detector an.
*/
IplImage* DataMatrixReader::processCanny(IplImage *sourceGrayImage)
{
int threshold1 = 100;
int threshold2 = 150;
int matrixSize = 3;
IplImage *cannyResultImage = cvCreateImage(cvGetSize(sourceGrayImage), 8, 1); // 1 Farbe
cvCanny(sourceGrayImage, cannyResultImage, threshold1, threshold2, matrixSize);
QStringList cannyResultImageData;
cannyResultImageData.append("Threshold 1: " + QString::number(threshold1));
cannyResultImageData.append("Threshold 1: " + QString::number(threshold2));
cannyResultImageData.append("Matrix size (for sobel): " + QString::number(matrixSize));
this->saveAndSendImage(cannyResultImage, "CannyResultImage.jpg", "Canny result image",
cannyResultImageData);
return cannyResultImage;
}
/*
* Berechnet aus den übergebenen DataMatrix Eckpunkten eine Region of Interest
* und gibt ein neues Bild bestehend aus dieser ROI zurück.
*/
IplImage* DataMatrixReader::createROI(IplImage *currentWorkImage, CvPoint *dataMatrixEdges, int finderPos)
{
int x_rect, y_rect, roi_width, roi_height;
x_rect = dataMatrixEdges[(finderPos + 1) % 4].x;
y_rect = dataMatrixEdges[(finderPos + 1) % 4].y;
roi_width = dataMatrixEdges[finderPos].y - dataMatrixEdges[(finderPos + 1) % 4].y;
roi_height = roi_width;
CvRect roi_rect = cvRect(x_rect, y_rect, roi_width, roi_height);
IplImage* currentROIImage = cvCreateImageHeader(cvSize(roi_width, roi_height),
currentWorkImage->depth,
currentWorkImage->nChannels);
currentROIImage->origin = currentWorkImage->origin;
currentROIImage->widthStep = currentWorkImage->widthStep;
currentROIImage->imageData = currentWorkImage->imageData + roi_rect.y * currentWorkImage->widthStep +
roi_rect.x * currentWorkImage->nChannels;
QStringList currentROIImageData;
this->saveAndSendImage(currentROIImage, "CurrentROIImage.jpg", "Current work image with ROI",
currentROIImageData);
return currentROIImage;
}
/*
* Entfernt die perspektivische Verzerrung des angegebenen Bildes.
*/
IplImage* DataMatrixReader::removePerspective(IplImage* currentWorkRotatedImage, CvPoint* edge, int finderPos)
{
/*-----------------------------------------------------------------------------
* Jetz noch die Perspektive rausnehmen
*-----------------------------------------------------------------------------*/
IplImage* transformedImg = cvCloneImage(currentWorkRotatedImage);
transformedImg->origin = currentWorkRotatedImage->origin;
cvSet(transformedImg, cvScalarAll(0), 0);
CvPoint2D32f srcQuad[4], dstQuad[4];
CvMat* warp_matrix = cvCreateMat(3, 3, CV_32FC1);
/*-----------------------------------------------------------------------------
* Zuweisung der verzerrten Ecken der Matrix
*-----------------------------------------------------------------------------*/
srcQuad[0].x = edge[(finderPos +1) % 4].x;
srcQuad[0].y = edge[(finderPos +1) % 4].y;
srcQuad[1].x = edge[(finderPos +2) % 4].x;
srcQuad[1].y = edge[(finderPos +2) % 4].y;
srcQuad[2].x = edge[finderPos].x;
srcQuad[2].y = edge[finderPos].y;
srcQuad[3].x = edge[(finderPos +3) % 4].x;
srcQuad[3].y = edge[(finderPos +3) % 4].y;
double kantenlaenge = edge[finderPos].y - edge[(finderPos + 1) % 4].y;
/*-----------------------------------------------------------------------------
* Zuweisungspunkte der entzerrten Matrix. Der linke Schenkel des finders
* befindet sich bereits in der gewünschten Position und wird als Masstab
* genommen. Eine Vergrösserung oder Verkleinerung der Matrix wäre hier
* möglich.
*-----------------------------------------------------------------------------*/
dstQuad[0].x = edge[(finderPos +1) % 4].x;
dstQuad[0].y = edge[(finderPos +1) % 4].y;
dstQuad[1].x = edge[(finderPos +1) % 4].x + kantenlaenge;
dstQuad[1].y = edge[(finderPos +1) % 4].y;
dstQuad[2].x = edge[finderPos].x;
dstQuad[2].y = edge[finderPos].y;
dstQuad[3].x = edge[finderPos].x + kantenlaenge;
dstQuad[3].y = edge[finderPos].y;
cvGetPerspectiveTransform(srcQuad, dstQuad, warp_matrix);
cvWarpPerspective(currentWorkRotatedImage, transformedImg, warp_matrix);
QStringList transformedImgData;
// Die Quellpunkte ausgeben:
for (int i = 0; i < 4; i++)
{
transformedImgData.append("Source point transformation " + QString::number(i+1) + ": " +
this->cvPointToString(srcQuad[i]));
}
// Die Zielpunkte ausgeben:
for (int i = 0; i < 4; i++)
{
transformedImgData.append("Dest. point transformation " + QString::number(i+1) + ": " +
this->cvPointToString(dstQuad[i]));
}
this->saveAndSendImage(transformedImg, "TransformedWorkImage.jpg",
"Current transformed work image", transformedImgData);
return transformedImg;
}
/*
* Zeichnet die übergebenen Ecken der DataMatrix in der übergebene Bild ein.
*/
void DataMatrixReader::paintDataMatrixEdges(IplImage *currentWorkRotatedImage, CvPoint *edge, CvPoint finder)
{
IplImage* currentRotatedImage = cvCreateImage( cvGetSize(currentWorkRotatedImage), 8, 3 ); // 3 Farben
cvConvertImage(currentWorkRotatedImage, currentRotatedImage, CV_GRAY2BGR);
for(int i = 0; i < 4; i++)
{
cvLine( currentRotatedImage, edge[i], edge[(i + 1) % 4], CV_RGB(255, 0, 0), 1, 8);
}
cvCircle(currentRotatedImage, edge[0], 8, CV_RGB(255, 0, 0), 2, 8, 0);
cvCircle(currentRotatedImage, finder, 20, CV_RGB(0, 255, 0), 2, 8, 0);
cvCircle(currentRotatedImage, edge[1], 8, CV_RGB(0, 255, 0), 2, 8, 0);
cvCircle(currentRotatedImage, edge[2], 8, CV_RGB(0, 0, 255), 2, 8, 0);
cvCircle(currentRotatedImage, edge[3], 8, CV_RGB(255, 188, 0), 2, 8, 0);
QStringList currentRotatedImageData;
for (int i = 0; i < 4; i++)
{
currentRotatedImageData.append("Data matrix edge " + QString::number(i+1) +
": " + this->cvPointToString(edge[i]));
}
this->saveAndSendImage(currentRotatedImage, "CurrentRotatedImageWithPoints.jpg",
"Current work image. Correct rotated and with edge points.",
currentRotatedImageData);
}
/*
* Berechnet den fehlenden vierten Punkt der DataMatrix.
*/
void DataMatrixReader::calculateMissingPoint(CvPoint* edge, int finderPos, CvPoint max)
{
/*-----------------------------------------------------------------------------
* Berechnen des fehlenden Punktes aus edge[finderPos] und max
* pt_high = höher gelegener der beiden bekannten Punkte
* pt_low = der Andere. Siehe auch nächsten Kommentar.
*-----------------------------------------------------------------------------*/
CvPoint ursprung_regional, pt_low, pt_high;
double m1, m2, diff_y1, diff_y2, diff_x, x_np, y_np;
/*-----------------------------------------------------------------------------
* Die Punkte nach oben und unten zu sortieren scheint nicht so gut.
* Besser nach links und rechts. Meistens ist der Linke auch der höhere,
* aber nicht immer !
*-----------------------------------------------------------------------------*/
if( edge[(finderPos + 2) % 4].x < max.x) // Einen der beiden Punkte als oberen
{
pt_low = max; // der rechte Punkt
pt_high = edge[(finderPos +2 ) % 4];
}
else
{
pt_low = edge[(finderPos + 2) % 4];
pt_high = max;
}
int nenner; // verhindert Division durch null
/*-----------------------------------------------------------------------------
* m1: Steigung der Matrixkante von oben links nach oben rechts
*-----------------------------------------------------------------------------*/
nenner = pt_high.x - edge[(finderPos + 1) % 4].x;
if (nenner == 0)
{
nenner++;
}
m1 = (double)(edge[(finderPos + 1) % 4].y - pt_high.y) / nenner;
//cout << "Nenner : " << nenner << endl;
/*-----------------------------------------------------------------------------
* m1: Steigung der Matrixkante von unten rechts nach oben rechts
*-----------------------------------------------------------------------------*/
nenner = pt_low.x - edge[(finderPos + 3) % 4].x;
if (nenner == 0)
{
nenner++;
}
m2 = (double)(edge[(finderPos + 3) % 4].y - pt_low.y) / nenner;
/*-----------------------------------------------------------------------------
* Zu den zu untersuchenden Punkten wird ein Hilfkoordinatensystem kon-
* struiert. Die angegebene Differenzen beschreiben Dreiecke, die zur Be-
* stimmung des noch nötigen Punktes fehlen. Es kommen lediglich die
* Strahlensätze zum Einsatz.
* Es wird der Schnittpunkt folgender Geraden berechnet:
* f1(x) = m1 * x + diff_y1
* f2(x) = m2 * x - diff_y2
* diff_x dient als Hilfsvariable zur Berechnung von diff_y2
*-----------------------------------------------------------------------------*/
diff_y1 = pt_low.y - pt_high.y;
diff_x = pt_low.x - pt_high.x;
diff_y2 = m2 * diff_x;
ursprung_regional.x = pt_low.x - diff_x;
ursprung_regional.y = pt_high.y + diff_y1;
/*-----------------------------------------------------------------------------
* Berechnen der Koordinaten zu Ursprung des Bildes und Zuweisung der Werte
* an die dem Finder sich befindende Position. Hiermit sind nun alle 4 Ecken
* der Matrix bestimmt.
*-----------------------------------------------------------------------------*/
x_np = (-diff_y2 - diff_y1) / ( m1 - m2 );