-
Notifications
You must be signed in to change notification settings - Fork 7
/
mainwindow.cpp
2013 lines (1683 loc) · 89.6 KB
/
mainwindow.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
/*#-------------------------------------------------
#
# Segmentation to Depthmap to 3D with openCV
#
# by AbsurdePhoton - www.absurdephoton.fr
#
# v1.5 - 2019/07/08
#
#-------------------------------------------------*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QMouseEvent>
#include <QScrollBar>
#include <QCursor>
#include <QColorDialog>
#include <QSizeGrip>
#include <QGridLayout>
#include <QDesktopWidget>
#include "mat-image-tools.h"
#include "dispersion3D.h"
using namespace cv;
using namespace cv::ximgproc;
using namespace std;
/////////////////// Window init //////////////////////
void MainWindow::AddCurveItem(const QString &title, const QColor &color, const QString &tip) // used to add gray gradient curves to the list
{
QListWidgetItem *item = new QListWidgetItem (); // create new label
item->setText(title); // set name to current label
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); // item enabled and selectable
item->setSelected(false); // but don't select it !
item->setForeground(color); // text color
item->setToolTip(tip); // help bubble
ui->listWidget_gradient_curve->addItem(item); // add new item to the list
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// window
setWindowFlags((((windowFlags() | Qt::CustomizeWindowHint)
& ~Qt::WindowCloseButtonHint) | Qt::WindowMinMaxButtonsHint)); // don't show buttons in title bar
this->setWindowState(Qt::WindowMaximized); // maximize window
setFocusPolicy(Qt::StrongFocus); // catch keyboard and mouse in priority
// add size grip to openGL widget
ui->openGLWidget_3d->setWindowFlags(Qt::SubWindow);
QSizeGrip * sizeGrip = new QSizeGrip(ui->openGLWidget_3d);
QGridLayout * layout = new QGridLayout(ui->openGLWidget_3d);
layout->addWidget(sizeGrip, 0,0,1,1,Qt::AlignBottom | Qt::AlignRight);
// populate gray gradient curve combobox
ui->listWidget_gradient_curve->blockSignals(true); // don't trigger automatic actions for these widgets
AddCurveItem("LINEAR", QColor(0,128,0), "Gray levels go straight from beginning to end\n f(x) = x");
AddCurveItem("COSINUS²", QColor(0,0,128), "Gray levels are spread a bit more at beginning and end\n f(x)=cos(pi/2-x*pi/2)²");
AddCurveItem("SIGMOID", QColor(0,0,128), "S-shaped gray levels\n1/3 beginning 1/3 gradient 1/3 end\n f(x)=1/(1 + e(-5*(2x -1))");
AddCurveItem("COSINUS", QColor(128,128,0), "Fast beginning and strong end grays\n f(x)=cos(pi/2-x*pi/2)");
AddCurveItem("COS²SQRT", QColor(128,128,0), "Center grays are predominant\n f(x)=cos(pi/2−sqrt(x)*pi/2)²");
AddCurveItem("POWER²", QColor(128,64,0), "1/3 of beginning level then gradient for the rest, fast ending\n f(x)=x²");
AddCurveItem("COS²POWER2", QColor(128,64,0), "Very strong beginning then gradient\n f(x)=cos(pi/2−x²∙pi/2)²");
AddCurveItem("POWER³", QColor(128,64,0), "Very strong beginning and fast ending\n f(x)=x³");
AddCurveItem("UNDULATE", QColor(128,0,0), "Waves modulated by gray levels range\n f(x)=cos(x/4*pi)");
AddCurveItem("UNDULATE²", QColor(128,0,0), "Increasing waves modulated by gray levels range\n f(x)=cos((x*2*pi)²)/2+0.5");
AddCurveItem("UNDULATE+", QColor(128,0,0), "Increasing levels of gray stripes\n f(x)=f(x) = cos(pi²∙(x+2.085)²) / ((x+2.085)³+10) + (x+2.085) − 2.11");
ui->listWidget_gradient_curve->blockSignals(false);
// populate tints comboBox
ui->comboBox_3d_tint->addItem(QIcon(":/icons/color.png"), "Color");
ui->comboBox_3d_tint->addItem(QIcon(":/icons/gray.png"), "Gray");
ui->comboBox_3d_tint->addItem(QIcon(":/icons/anaglyph.png"), "True Red-Cyan");
ui->comboBox_3d_tint->addItem(QIcon(":/icons/image-off.png"), "Half-tint");
ui->comboBox_3d_tint->addItem(QIcon(":/icons/image.png"), "Optimized");
ui->comboBox_3d_tint->addItem(QIcon(":/icons/compute.png"), "Dubois");
// other UI elements
ui->frame_gradient->setEnabled(false); // only enabled when a segmentation or depthmap XML file is loaded
ui->spinBox_3d_resolution->setValue(ui->openGLWidget_3d->width()); // default size openGL widget
// initial variable values
InitializeValues();
}
MainWindow::~MainWindow()
{
delete ui;
}
/////////////////// GUI //////////////////////
void MainWindow::InitializeValues() // Global variables init
{
loaded = false; // main image NOT loaded
zoom = 1; // init zoom
oldZoom = 1; // to detect a zoom change
zoom_type = ""; // not set now, can be "button" or (mouse) "wheel"
basedirinifile = QDir::currentPath().toUtf8().constData();
basedirinifile += "/dir.ini";
cv::FileStorage fs(basedirinifile, FileStorage::READ); // open dir ini file
if (fs.isOpened()) {
fs["BaseDir"] >> basedir; // load labels
}
else basedir = "/home/"; // base path and file
basefile = "example";
nbLabels = 0; // no labels yet
updateVertices3D = false; // not an update
computeVertices3D = true; // update openGL widget vertices now
ui->openGLWidget_3d->computeIndexes3D = true; // update openGL widget indexes now
computeColors3D = true; // update openGL widget colors now
moveBegin = false; // not moving any arrow now
moveEnd = false;
// load 3D example
image = QImage2Mat(QImage(":/example/absurdephoton-image.png"));
depthmap = QImage2Mat(QImage(":/example/absurdephoton-depthmap.png"));
cvtColor(depthmap, depthmap, COLOR_BGR2GRAY);
ui->openGLWidget_3d->image3D = image; // transfer data to widget
ui->openGLWidget_3d->depthmap3D = depthmap;
ui->openGLWidget_3d->area3D = Rect(0, 0, image.cols,image.rows);
ui->openGLWidget_3d->mask3D = Mat::zeros(image.rows, image.cols, CV_8UC1);
ui->openGLWidget_3d->depth3D = 1; // initial view
ui->openGLWidget_3d->anaglyphShift = -1.5;
ui->openGLWidget_3d->computeVertices3D = true; // recompute 3D vertices
ui->openGLWidget_3d->computeIndexes3D = true; // recompute 3D indexes
ui->openGLWidget_3d->computeColors3D = true; // recompute 3D colors
ui->openGLWidget_3d->update(); // apply !
}
void MainWindow::on_button_quit_clicked()
{
int quit = QMessageBox::question(this, "Quit this wonderful program", "Are you sure you want to quit?", QMessageBox::Yes|QMessageBox::No); // quit, are you sure ?
if (quit == QMessageBox::No) // don't quit !
return;
QCoreApplication::quit();
}
/////////////////// Labels //////////////////////
int MainWindow::GetCurrentLabelNumber() // label number for use with "label" mask
{
return ui->listWidget_labels->currentItem()->data(Qt::UserRole).toInt(); // label number stored in this special field
}
void MainWindow::DeleteAllLabels() // delete all labels in the list
{
ui->listWidget_labels->blockSignals(true); // the labels list must not trigger any action
ui->listWidget_labels->clear(); // delete all labels
ui->listWidget_labels->blockSignals(false); // return to normal
}
void MainWindow::BlockGradientsSignals(const bool &active) // block or not all gradient elements signals
{
ui->horizontalSlider_begin->blockSignals(active);
ui->horizontalSlider_end->blockSignals(active);
ui->spinBox_color_begin->blockSignals(active);
ui->spinBox_color_end->blockSignals(active);
ui->radioButton_flat->blockSignals(active);
ui->radioButton_linear->blockSignals(active);
ui->radioButton_double_linear->blockSignals(active);
ui->radioButton_radial->blockSignals(active);
ui->listWidget_gradient_curve->blockSignals(active);
}
void MainWindow::on_listWidget_labels_currentItemChanged(QListWidgetItem *currentItem) // several actions when label changes
{
ui->label_name->setText(currentItem->text()); // display label name as current
int id = currentItem->data(Qt::UserRole).toInt(); // get label id
currentLabelMask = labels == id; // extract label using its id
selection = 0; // erase selection mask
//selection.setTo(Vec3b(0, 32, 32), mask_temp); // fill with dark yellow
vector<vector<cv::Point>> contours;
vector<Vec4i> hierarchy;
findContours(currentLabelMask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // find new cell contours
selection_rect = boundingRect(contours[0]); // find biggest rectangle
for (uint n = 1; n < contours.size(); n++) { // ... by cycling through all found contours
Rect rect_temp = boundingRect(contours[n]); // current Rect
if (rect_temp.x < selection_rect.x) { // adjust size
selection_rect.width += selection_rect.x - rect_temp.x;
selection_rect.x = rect_temp.x;
}
if (rect_temp.y < selection_rect.y) {
selection_rect.height += selection_rect.y - rect_temp.y;
selection_rect.y = rect_temp.y;
}
if (rect_temp.x + rect_temp.width > selection_rect.x + selection_rect.width)
selection_rect.width = rect_temp.x + rect_temp.width - selection_rect.x;
if (rect_temp.y + rect_temp.height > selection_rect.y + selection_rect.height)
selection_rect.height = rect_temp.y + rect_temp.height - selection_rect.y;
}
ui->openGLWidget_3d->area3D = selection_rect; // update opengl widget elements
ui->openGLWidget_3d->mask3D = currentLabelMask;
drawContours(selection, contours, -1, Vec3b(0, 255, 255), 1, 8, hierarchy ); // draw contour of new cell in selection mask
/*cv::rectangle(selection, Rect(selection_rect.x, selection_rect.y, selection_rect.width, selection_rect.height),
Vec3b(255, 255, 255), 2); // draw entire selection rectangle*/
BlockGradientsSignals(true); // don't trigger automatic actions for these widgets
int row = ui->listWidget_labels->currentRow(); // get current row of the list to access array indexed on it
switch (gradients[row].gradient) { // gradient type ?
case gradient_flat: {
ui->radioButton_flat->setChecked(true); // set correspondng radio button
break;
}
case gradient_linear: {
ui->radioButton_linear->setChecked(true);
break;
}
case gradient_doubleLinear: {
ui->radioButton_double_linear->setChecked(true);
break;
}
case gradient_radial: {
ui->radioButton_radial->setChecked(true);
break;
}
}
ui->horizontalSlider_begin->setValue(gradients[row].beginColor); // show begin and end colors
ui->horizontalSlider_end->setValue(gradients[row].endColor);
ui->spinBox_color_begin->setValue(gradients[row].beginColor);
ui->spinBox_color_end->setValue(gradients[row].endColor);
ui->listWidget_gradient_curve->setCurrentRow(gradients[row].curve); // and the gray gradient curve type
BlockGradientsSignals(false); // signals : return to normal
ShowGradient(); // show the nice gradient example
Render(); // update global view
}
/////////////////// Save and load //////////////////////
void MainWindow::SaveDirBaseFile()
{
cv::FileStorage fs(basedirinifile, cv::FileStorage::WRITE); // open dir ini file for writing
fs << "BaseDir" << basedir; // write folder name
fs.release(); // close file
}
void MainWindow::ChangeBaseDir(QString filename) // Set base dir and file
{
basefile = filename.toUtf8().constData(); // base file name and dir are used after to save other files
// Remove extension if present
size_t period_idx = basefile.rfind('.');
if (std::string::npos != period_idx)
basefile.erase(period_idx);
basedir = basefile;
size_t found = basefile.find_last_of("\\/"); // find last directory
std::string separator = basefile.substr(found,1); // copy path separator (Linux <> Windows)
basedir = basedir.substr(0,found) + separator; // define base path
basefile = basefile.substr(found+1); // delete path in base file
SaveDirBaseFile(); // Save current path to ini file
}
void MainWindow::DisableGUI() // reset entire GUI - used when something goes wrong when loading files
{
loaded = false;
ui->label_viewport->setPixmap(QPixmap());
ui->label_thumbnail->setPixmap(QPixmap());
ui->frame_gradient->setEnabled(false);
image.release();
depthmap.release();
labels.release();
ui->openGLWidget_3d->image3D.release();
ui->openGLWidget_3d->depthmap3D.release();
ui->openGLWidget_3d->computeVertices3D = true;
ui->openGLWidget_3d->computeColors3D = true;
ui->openGLWidget_3d->update();
DeleteAllLabels(); // delete all labels but do not create a new one
ui->label_filename->setText("Please load a file"); // delete file name in ui
QApplication::restoreOverrideCursor(); // Restore cursor
}
void MainWindow::on_button_load_segmentation_clicked() // load segmentation XML file and corresponding image files
{
QString filename = QFileDialog::getOpenFileName(this, "Load segmentation from XML file...", QString::fromStdString(basedir + "*-segmentation-data.xml"), "*.xml *.XML"); // get file name
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
qApp->processEvents();
/*basefile = filename.toUtf8().constData(); // base file name and dir are used after to save other files
size_t pos = basefile.find(".xml");
if (pos != std::string::npos) basefile.erase(pos, basefile.length());
basedir = basefile;
size_t found = basefile.find_last_of("/"); // find last directory
basedir = basedir.substr(0,found) + "/"; // extract file location
basefile = basefile.substr(found+1); // delete ending slash
SaveDirBaseFile(); // Save current path to ini file*/
ChangeBaseDir(filename);
size_t pos = basefile.find("-segmentation-data"); // the XML file must end with this
if (pos != std::string::npos) // yes !
basefile.erase(pos, basefile.length());
else { // doesn't end with "-segmentation-data"
QMessageBox::critical(this, "File name error",
"There was a problem reading the segmentation mask file:\nit must end with ''-segmentation-data.xml''");
DisableGUI(); // problem : reset GUI elements and exit
return;
}
ui->label_filename->setText(filename); // display file name in GUI
std::string filesession = filename.toUtf8().constData(); // base file name
pos = filesession.find("-segmentation-data.xml"); // ends with "-segmentation-data.xml"
if (pos != std::string::npos) filesession.erase(pos, filesession.length()); // this is what will be used to name files hereafter
depthmap = cv::imread(filesession + "-segmentation-mask.png", IMREAD_COLOR); // load segmentation mask
if (depthmap.empty()) { // mask empty, not good !
QMessageBox::critical(this, "File error",
"There was a problem reading the segmentation mask file:\nit must end with ''-segmentation-mask.png''");
DisableGUI(); // problem : reset GUI elements and exit
return;
}
image = cv::imread(filesession + "-segmentation-image.png"); // load reference image
if (image.empty()) {
QMessageBox::critical(this, "File error",
"There was a problem reading the segmentation image file:\nit must end with ''-segmentation-image.png''");
DisableGUI();
return;
}
if ((image.cols != depthmap.cols) | (image.rows != depthmap.rows)) { // image and mask sizes not the same -> not good !
QMessageBox::critical(this, "Image size error",
"The image and mask image size (width and height) differ");
DisableGUI();
return;
}
depthmap = Mat::zeros(image.rows, image.cols, CV_8UC1); // initialize depthmap mask to image size
selection = Mat::zeros(image.rows, image.cols, CV_8UC3); // initialize selection mask to image size
DeleteAllLabels(); // delete all labels in the list
cv::FileStorage fs(filesession + "-segmentation-data.xml", FileStorage::READ); // open labels file
if (!fs.isOpened()) { // file not found ? this error is not handled by the above instructions
QMessageBox::critical(this, "File error",
"There was a problem reading the segmentation data file:\nit must end with ''-segmentation-data.xml''");
DisableGUI();
return;
}
labels.release(); // reset labels data
try { // try to load labels data
fs["LabelsMask"] >> labels; // load labels mask
}
catch( cv::Exception& e ) // problem ?
{
const char* err_msg = e.what();
QMessageBox::critical(this, "XML Segmentation file error",
"There was a problem reading the segmentation XML file\nThe \"LabelsMask\" data is wrong\nError:\n"
+ QString(err_msg));
DisableGUI();
return;
}
nbLabels = 0; // time to read each label specific data - initialize labels count
fs["LabelsCount"] >> nbLabels; // read how many labels to load
if (nbLabels <= 0) { // no labels ?
QMessageBox::critical(this, "XML Segmentation file error",
"There was a problem reading the segmentation XML file\nThe data is wrong");
DisableGUI();
return;
}
ui->listWidget_labels->blockSignals(true); // the labels list must not trigger any action
for (int i = 0; i < nbLabels; i++) { // for each label to load
int num = -1;
std::string name = "###Error###"; // errors are not handled here, better set rubbish values, the user will see it anyway
QListWidgetItem *item = new QListWidgetItem (); // create new label item
std::string field;
field = "LabelId" + std::to_string(i); // read label id
fs [field] >> num;
item->setData(Qt::UserRole, num); // set it to current label
field = "LabelName" + std::to_string(i); // read label name
fs [field] >> name;
item->setText(QString::fromStdString(name)); // set name to current label
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); // item enabled, editable and selectable
ui->listWidget_labels->addItem(item); // add the label item to the list
item->setSelected(false); // but don't select it !
Mat1b mask_temp = labels == num; // extract label to temp depthmap
Moments m = moments(mask_temp, false); // compute the barycenter of the label representation
cv::Point p(m.m10/m.m00, m.m01/m.m00);
uchar col = int(round(double(p.y) / image.rows * 255)); // set an arbitray gray level based on the barycenter height in image
depthmap.setTo(col, mask_temp); // color this label mask in global depthmap with barycenter color
// set values in the gradients array corresponding to to label id
gradients[i].beginColor = col; // gradient begin and end color are barycenter color
gradients[i].endColor = col;
gradients[i].beginPoint = p; // begin point of gradient arrow is the barycenter
if (p.y - 50 > 0) // the arrow is 50 pixels long (vertical), the head should stay in the image rectangle
gradients[i].endPoint = cv::Point(p.x, p.y - 50);
else
gradients[i].endPoint = cv::Point(p.x, p.y + 50);
gradients[i].gradient = gradient_flat; // gradient flat at first
gradients[i].curve = curve_linear; // and gradient curve set to linear
}
fs.release(); // close file
loaded = true; // we've done it !
ui->label_thumbnail->setPixmap(QPixmap()); // flush current thumbnail
ui->label_viewport->setPixmap(QPixmap()); // delete viewport
ui->horizontalScrollBar_viewport->setMaximum(0); // update scrollbars
ui->verticalScrollBar_viewport->setMaximum(0);
ui->horizontalScrollBar_viewport->setValue(0);
ui->verticalScrollBar_viewport->setValue(0);
ui->label_image_width->setText(QString::number(image.cols)); // display image dimensions
ui->label_image_height->setText(QString::number(image.rows));
ui->checkBox_image->setChecked(false);
ui->checkBox_depthmap->setChecked(true);
ui->checkBox_3d_blur->setChecked(false); // several options that should be reset in GUI
ui->comboBox_3d_tint->setCurrentIndex(0);
ui->doubleSpinBox_gamma->setValue(1);
ui->frame_gradient->setEnabled(true);
double zoomX = double(ui->label_viewport->width()) / image.cols; // find the best fit for the viewport : try vertical and horizontal ratios
double zoomY = double(ui->label_viewport->height()) / image.rows;
if (zoomX < zoomY) zoom = zoomX; // the lowest fits the view
else zoom = zoomY;
oldZoom = zoom; // no zoom change
ShowZoomValue(); // display current zoom value
viewport = Rect(0, 0, image.cols, image.rows); // update viewport size
thumbnail = ResizeImageAspectRatio(image, cv::Size(ui->label_thumbnail->width(),ui->label_thumbnail->height())); // create thumbnail
ShowThumbnail();
ui->openGLWidget_3d->depthmap3D = depthmap; // initialize 3D view data
ui->openGLWidget_3d->image3D = image;
computeVertices3D = true; // update openGL widget vertices
ui->openGLWidget_3d->computeIndexes3D = true; // update openGL widget indexes
computeColors3D = true; // update openGL widget colors
ui->listWidget_labels->blockSignals(false); // return to normal for labels
ui->listWidget_labels->setCurrentRow(0); // and select the first item
QApplication::restoreOverrideCursor(); // Restore cursor
//QMessageBox::information(this, "Load segmentation session", "Session loaded with base name:\n" + QString::fromStdString(filesession));
}
void MainWindow::on_button_save_depthmap_clicked() // save XML and image depthmap files
{
if (!loaded) { // nothing loaded yet = get out
QMessageBox::warning(this, "Nothing to save",
"Not now!\n\nBefore anything else, load a Segmentation or Depthmap project");
return;
}
QString filename = QFileDialog::getSaveFileName(this, "Save depthmap to XML file...", "./" + QString::fromStdString(basedir + basefile + "-depthmap-data.xml"), "*.xml *.XML"); // filename
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
qApp->processEvents();
/*// base file name and dir can change so reset them
basefile = filename.toUtf8().constData(); // base file name and dir are used after to save other files
size_t pos = basefile.find(".xml");
if (pos != std::string::npos) basefile.erase(pos, basefile.length());
basedir = basefile;
size_t found = basefile.find_last_of("/"); // find last directory
basedir = basedir.substr(0,found) + "/"; // extract file location
basefile = basefile.substr(found+1); // delete ending slash*/
ChangeBaseDir(filename);
size_t pos = basefile.find("-depthmap-data");
if (pos != std::string::npos) basefile.erase(pos, basefile.length());
std::string filesession = filename.toUtf8().constData();
pos = filesession.find("-depthmap-data.xml"); // use base file name
if (pos != std::string::npos) filesession.erase(pos, filesession.length());
pos = filesession.find(".xml"); // use base file name
if (pos != std::string::npos) filesession.erase(pos, filesession.length());
bool write;
Mat depthmap_temp;
cvtColor(depthmap, depthmap_temp, COLOR_GRAY2RGB);
write = cv::imwrite(filesession + "-depthmap-mask.png", depthmap_temp); // save depthmap mask
if (!write) { // problem ?
QApplication::restoreOverrideCursor(); // Restore cursor
QMessageBox::critical(this, "File error",
"There was a problem saving the depthmap mask image file");
return;
}
write = cv::imwrite(filesession + "-depthmap-image.png", image); // save reference image
if (!write) { // problem ?
QApplication::restoreOverrideCursor(); // Restore cursor
QMessageBox::critical(this, "File error",
"There was a problem saving the depthmap image file");
return;
}
cv::FileStorage fs(filesession + "-depthmap-data.xml", cv::FileStorage::WRITE); // open depthmap XML file for writing
if (!fs.isOpened()) { // problem ?
QApplication::restoreOverrideCursor(); // Restore cursor
QMessageBox::critical(this, "File error",
"There was a problem writing the depthmap data file");
return;
}
fs << "LabelsCount" << nbLabels; // write labels count
for (int i = 0; i < nbLabels; i++) { // for each label
std::string field;
QListWidgetItem *item = ui->listWidget_labels->item(i); // get label id
field = "LabelId" + std::to_string(i);
fs << field << item->data(Qt::UserRole).toInt(); // write label id
std::string name = item->text().toUtf8().constData(); // write label name
field = "LabelName" + std::to_string(i);
fs << field << name;
field = "GradientType" + std::to_string(i);
fs << field << gradients[i].gradient; // write gradient type
field = "GradientCurve" + std::to_string(i);
fs << field << gradients[i].curve; // write gradient curve
field = "GradientBeginColor" + std::to_string(i);
fs << field << gradients[i].beginColor; // write gradient begin color
field = "GradientEndColor" + std::to_string(i);
fs << field << gradients[i].endColor; // write gradient end color
field = "GradientBeginPoint" + std::to_string(i);
fs << field << gradients[i].beginPoint; // write gradient begin point
field = "GradientEndPoint" + std::to_string(i);
fs << field << gradients[i].endPoint; // write gradient end point
}
fs << "Labels" << labels; // write labels data
fs.release(); // close file
ui->label_filename->setText(QString::fromStdString(filesession + "-depthmap-data.xml")); // display new file name in ui
QApplication::restoreOverrideCursor(); // Restore cursor
QMessageBox::information(this, "Save depthmap session", "Session successfuly saved with base name:\n" + QString::fromStdString(basefile));
}
void MainWindow::on_button_load_depthmap_clicked() // load depthmap XML file
{
QString filename = QFileDialog::getOpenFileName(this, "Load depthmap from XML file...", QString::fromStdString(basedir + "*-depthmap-data.xml"), "*.xml *.XML"); // file name
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
qApp->processEvents();
/*basefile = filename.toUtf8().constData(); // base file name and dir are used after to save other files
size_t pos = basefile.find(".xml");
if (pos != std::string::npos) basefile.erase(pos, basefile.length());
basedir = basefile;
size_t found = basefile.find_last_of("/"); // find last directory
basedir = basedir.substr(0,found) + "/"; // extract file location
SaveDirBaseFile(); // Save current path to ini file
basefile = basefile.substr(found+1); // delete ending slash*/
ChangeBaseDir(filename);
size_t pos = basefile.find("-depthmap-data");
if (pos != std::string::npos)
basefile.erase(pos, basefile.length());
else { // doesn't end with "-depthmap-data"
QMessageBox::critical(this, "File name error",
"There was a problem reading the depthmap file:\nit must end with ''-depthmap-data.xml''");
DisableGUI(); // problem : reset GUI elements and exit
return;
}
std::string filesession = filename.toUtf8().constData(); // base file name
pos = filesession.find("-depthmap-data.xml"); // ends with "depthmap-data.xml"
if (pos != std::string::npos) filesession.erase(pos, filesession.length());
depthmap = cv::imread(filesession + "-depthmap-mask.png", IMREAD_COLOR); // load depthmap mask
if (depthmap.channels() > 1)
cvtColor(depthmap, depthmap, COLOR_BGR2GRAY);
if (depthmap.empty()) { // problem ?
QMessageBox::critical(this, "File error",
"There was a problem reading the depthmap mask file:\nit must end with ''-depthmap-mask.png''");
DisableGUI();
return;
}
image = cv::imread(filesession + "-depthmap-image.png"); // load reference image
if (image.empty()) {
QMessageBox::critical(this, "File error",
"There was a problem reading the depthmap image file:\nit must end with ''-depthmap-image.png''");
DisableGUI();
return;
}
if ((image.cols != depthmap.cols) | (image.rows != depthmap.rows)) { // image and mask sizes not the same -> not good !
QMessageBox::critical(this, "Image size error",
"The image and mask image size (width and height) differ");
DisableGUI();
return;
}
selection = Mat::zeros(image.rows, image.cols, CV_8UC3); // initialize selection mask to image size
DeleteAllLabels(); // delete all labels in the list
cv::FileStorage fs(filesession + "-depthmap-data.xml", FileStorage::READ); // open labels file
if (!fs.isOpened()) { // file not opened, not handled by above instructions
QMessageBox::critical(this, "File error",
"There was a problem reading the depthmap data file:\nit must end with ''-depthmap-data.xml''");
DisableGUI();
return;
}
Mat labels_temp = Mat::zeros(image.rows, image.cols, CV_32SC1); // labels on 1 channel
try { // try to read labels data
fs["Labels"] >> labels_temp; // load labels
}
catch( cv::Exception& e ) // problem ?
{
const char* err_msg = e.what(); // get error from openCV
QMessageBox::critical(this, "XML Depthmap file error",
"There was a problem reading the depthmap XML file\nThe \"Labels\" data is wrong\nError:\n"
+ QString(err_msg));
DisableGUI();
return;
}
labels_temp.copyTo(labels); // valid data copied to labels
nbLabels = 0; // labels count
fs["LabelsCount"] >> nbLabels; // read how many labels to load ?
if (nbLabels <= 0) { // no labels ?
QMessageBox::critical(this, "XML Depthmap file error",
"There was a problem reading the depthmap XML file\nThe data is wrong");
DisableGUI();
return;
}
ui->listWidget_labels->blockSignals(true); // don't trigger events when populating labels list
for (int i = 0; i < nbLabels; i++) { // for each label to load
std::string name ="###Error###"; // init default values, no error handling this time, the user should see if there was a problem
int num = -1;
cv::Point point = cv::Point(0,0);
int color = 255;
int gtype = 0;
int gcurve = 0;
QListWidgetItem *item = new QListWidgetItem (); // create new label item
std::string field;
field = "LabelId" + std::to_string(i); // read label id
fs [field] >> num;
item->setData(Qt::UserRole, num); // set it to current label
field = "LabelName" + std::to_string(i); // read label name
fs [field] >> name;
item->setText(QString::fromStdString(name)); // set name to current label
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); // item enabled and selectable
ui->listWidget_labels->addItem(item); // add new item to labels list
item->setSelected(false); // don't select it !
field = "GradientType" + std::to_string(i);
fs [field] >> gtype; // load gradient type
gradients[i].gradient = gradientType(gtype);
field = "GradientCurve" + std::to_string(i);
fs [field] >> gcurve; // load curve type
gradients[i].curve = curveType(gcurve);
field = "GradientBeginColor" + std::to_string(i);
fs [field] >> color; // load gradient begin color
gradients[i].beginColor = color;
field = "GradientEndColor" + std::to_string(i);
fs [field] >> color; // load gradient end color
gradients[i].endColor = color;
field = "GradientBeginPoint" + std::to_string(i);
fs [field] >> point; // load gradient begin point
gradients[i].beginPoint = point;
field = "GradientEndPoint" + std::to_string(i);
fs [field] >> point; // load gradient end point
gradients[i].endPoint = point;
}
fs.release(); // close file
loaded = true; // all good !
ui->label_filename->setText(filename); // display file name in ui
ui->label_thumbnail->setPixmap(QPixmap());
ui->label_viewport->setPixmap(QPixmap()); // delete depthmap image
ui->horizontalScrollBar_viewport->setMaximum(0); // update scrollbars
ui->verticalScrollBar_viewport->setMaximum(0);
ui->horizontalScrollBar_viewport->setValue(0);
ui->verticalScrollBar_viewport->setValue(0);
ui->label_image_width->setText(QString::number(image.cols)); // display image dimensions
ui->label_image_height->setText(QString::number(image.rows));
ui->checkBox_image->setChecked(false);
ui->checkBox_depthmap->setChecked(true);
ui->checkBox_3d_blur->setChecked(false); // init several GUI items to default
ui->comboBox_3d_tint->setCurrentIndex(0);
ui->doubleSpinBox_gamma->setValue(1);
ui->frame_gradient->setEnabled(true); // enable gradients selection
double zoomX = double(ui->label_viewport->width()) / image.cols; // find best fit for the viewport, try vertical and horizontal ratios
double zoomY = double(ui->label_viewport->height()) / image.rows;
if (zoomX < zoomY) zoom = zoomX; // the lowest fits the view
else zoom = zoomY;
oldZoom = zoom; // zoom already good
ShowZoomValue(); // display current zoom
viewport = Rect(0, 0, image.cols, image.rows); // update viewport size
thumbnail = ResizeImageAspectRatio(image, cv::Size(ui->label_thumbnail->width(),ui->label_thumbnail->height())); // create thumbnail
ShowThumbnail(); // update thumbnail view
ui->openGLWidget_3d->depthmap3D = depthmap; // init new 3D scene
ui->openGLWidget_3d->image3D = image;
computeVertices3D = true; // update openGL widget vertices
ui->openGLWidget_3d->computeIndexes3D = true; // update openGL widget indexes
computeColors3D = true; // update openGL widget colors
ui->listWidget_labels->blockSignals(false); // return to normal for labels
ui->listWidget_labels->setCurrentRow(0); // select first row of the list
QApplication::restoreOverrideCursor(); // Restore cursor
//QMessageBox::information(this, "Load depthmap session", "Session loaded with base name:\n" + QString::fromStdString(filesession));
}
void MainWindow::on_button_load_rgbd_clicked() // load previous session
{
QString filename = QFileDialog::getOpenFileName(this, "Load RGB+D : image...", QString::fromStdString(basedir),
"Images (*.jpg *.JPG *.jpeg *.JPEG *.jp2 *.JP2 *.png *.PNG *.tif *.TIF *.tiff *.TIFF *.bmp *.BMP)"); // reference image file name
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
qApp->processEvents();
/*basefile = filename.toUtf8().constData(); // base file name and dir are used after to save other files
basefile = basefile.substr(0, basefile.size()-4); // strip file extension
basedir = basefile;
size_t found = basefile.find_last_of("/"); // find last directory
basedir = basedir.substr(0,found) + "/"; // extract file location
SaveDirBaseFile(); // Save current path to ini file
basefile = basefile.substr(found+1); // delete ending slash
ui->label_filename->setText(filename); // display file name in ui*/
ChangeBaseDir(filename);
std::string filesession = filename.toUtf8().constData(); // base file name
image = cv::imread(filesession); // load image
if (image.empty()) {
QMessageBox::critical(this, "File error", "There was a problem reading the image file");
DisableGUI();
return;
}
filename = QFileDialog::getOpenFileName(this, "Load RGB+D : depthmap...", QString::fromStdString(basedir),
"Images (*.jpg *.JPG *.jpeg *.JPEG *.jp2 *.JP2 *.png *.PNG *.tif *.TIF *.tiff *.TIFF *.bmp *.BMP)"); // depthmap file name
ChangeBaseDir(filename);
filesession = filename.toUtf8().constData(); // base file name
depthmap = cv::imread(filesession, IMREAD_COLOR); // load depthmap
if (depthmap.channels() > 1)
cvtColor(depthmap, depthmap, COLOR_BGR2GRAY);
if ((depthmap.empty()) | (image.cols != depthmap.cols) | (image.rows != depthmap.rows)) { // if image and depthmap sizes differ or depthmap empty
if ((image.cols != depthmap.cols) | (image.rows != depthmap.rows)) // sizes differ
QMessageBox::critical(this, "Image size error", "The image and depthmap size (width and height) must be the same.");
else
QMessageBox::critical(this, "File error", "There was a problem reading the depthmap file");
DisableGUI();
return;
}
selection = Mat::zeros(image.rows, image.cols, CV_8UC3); // initialize selection mask to image size
labels = Mat::zeros(image.rows, image.cols, CV_32SC1); // labels on 1 channel
DeleteAllLabels(); // delete all labels but do not create a new one
loaded = true; // loaded successfully !
ui->label_filename->setText(filename); // display file name in ui
ui->label_thumbnail->setPixmap(QPixmap()); // reinit several GUI elements
ui->label_viewport->setPixmap(QPixmap());
ui->checkBox_image->setChecked(true); // no need for that
ui->checkBox_depthmap->setChecked(false);
ui->frame_gradient->setEnabled(false);
ui->checkBox_3d_blur->setChecked(false); // reinit 3D view options
ui->comboBox_3d_tint->setCurrentIndex(0);
ui->doubleSpinBox_gamma->setValue(1);
ui->horizontalScrollBar_viewport->setMaximum(0); // update scrollbars
ui->verticalScrollBar_viewport->setMaximum(0);
ui->horizontalScrollBar_viewport->setValue(0);
ui->verticalScrollBar_viewport->setValue(0);
ui->label_image_width->setText(QString::number(image.cols)); // display image dimensions
ui->label_image_height->setText(QString::number(image.rows));
double zoomX = double(ui->label_viewport->width()) / image.cols; // find best fit for viewport, try vertical and horizontal ratios
double zoomY = double(ui->label_viewport->height()) / image.rows;
if (zoomX < zoomY) zoom = zoomX; // the lowest fits the view
else zoom = zoomY;
oldZoom = zoom; // zoom already set
ShowZoomValue(); // display current zoom
viewport = Rect(0, 0, image.cols, image.rows); // update viewport size
thumbnail = ResizeImageAspectRatio(image, cv::Size(ui->label_thumbnail->width(),ui->label_thumbnail->height())); // create thumbnail
CopyFromImage(image, viewport).copyTo(disp_color); // copy only the viewport part of image
QPixmap D;
D = Mat2QPixmapResized(disp_color, int(viewport.width*zoom), int(viewport.height*zoom), true); // zoomed image
ui->label_viewport->setPixmap(D); // Set new image content viewport
ShowThumbnail(); // update thumbnail view
ui->openGLWidget_3d->depthmap3D = depthmap; // init 3D scene
ui->openGLWidget_3d->image3D = image;
ui->openGLWidget_3d->area3D = Rect(0, 0, image.rows, image.cols);
ui->openGLWidget_3d->mask3D = Mat(image.rows, image.cols, CV_8UC1);
ui->openGLWidget_3d->computeVertices3D = true; // recompute the 3d scene
ui->openGLWidget_3d->computeIndexes3D = true; // update openGL widget indexes
ui->openGLWidget_3d->computeColors3D = true;
ui->openGLWidget_3d->update(); // view 3D scene
QApplication::restoreOverrideCursor(); // Restore cursor
//QMessageBox::information(this, "Load depthmap session", "Session loaded with base name:\n" + QString::fromStdString(filesession));
}
void MainWindow::on_button_save_ply_clicked() // save XML and image depthmap files
{
if (!loaded) { // nothing loaded yet = get out
QMessageBox::warning(this, "Nothing to save",
"Not now!\n\nBefore anything else, load a Segmentation or Depthmap project");
return;
}
QString filename = QFileDialog::getSaveFileName(this, "Save mesh to PLY file...", "./" + QString::fromStdString(basedir + basefile + ".ply"), "*.ply *.PLY"); // filename
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
qApp->processEvents();
ui->openGLWidget_3d->SaveToPly(filename);
QApplication::restoreOverrideCursor(); // Restore cursor
QMessageBox::information(this, "Export 3D mesh", "Mesh successfully exported with file name:\n" + filename);
}
/////////////////// Display controls //////////////////////
void MainWindow::on_checkBox_depthmap_clicked() // Refresh image : depthmap on/off
{
Render(); // update display
}
void MainWindow::on_checkBox_image_clicked() // Refresh image : image on/off
{
Render(); // update display
}
void MainWindow::on_horizontalSlider_blend_depthmap_valueChanged() // refresh image : blend depthmap transparency changed
{
Render(); // update display
}
void MainWindow::on_horizontalSlider_blend_image_valueChanged() // refresh image : image mask transparency changed
{
Render(); // update display
}
void MainWindow::on_horizontalScrollBar_viewport_valueChanged() // update viewport
{
viewport.x = ui->horizontalScrollBar_viewport->value(); // new value
Render(); // update display
}
void MainWindow::on_verticalScrollBar_viewport_valueChanged() // update viewport
{
viewport.y = ui->verticalScrollBar_viewport->value(); // new value
Render(); // update display
}
void MainWindow::ZoomPlus() // zoom in
{
int z = 0;
while (zoom >= zooms[z]) z++; // from lowest to highest value find the next one
if (z == num_zooms) z--; // maximum
if (zoom != zooms[z]) { // zoom changed ?
QApplication::setOverrideCursor(Qt::SizeVerCursor); // zoom cursor
qApp->processEvents();
oldZoom = zoom;
zoom = zooms[z]; // new zoom value
ShowThumbnail();
Render(); // update display
QApplication::restoreOverrideCursor(); // Restore cursor
}
}
void MainWindow::ZoomMinus() // zoom out
{
int z = num_zooms;
while (zoom <= zooms[z]) z--; // from highest to lowest value find the next one
if (z == 0) z++; // minimum
if (zoom != zooms[z]) { // zoom changed ?
QApplication::setOverrideCursor(Qt::SizeVerCursor); // zoom cursor
qApp->processEvents();
oldZoom = zoom;
zoom = zooms[z]; // new zoom value
ShowThumbnail();
Render(); // update display
QApplication::restoreOverrideCursor(); // Restore cursor
}
}
void MainWindow::on_pushButton_zoom_minus_clicked() // zoom out from button
{
zoom_type = "button";
ZoomMinus();
}
void MainWindow::on_pushButton_zoom_plus_clicked() // zoom in from button
{
zoom_type = "button";
ZoomPlus();
}
void MainWindow::on_pushButton_zoom_fit_clicked() // zoom fit from button
{
zoom_type = "button";
oldZoom = zoom;
double zoomX = double(ui->label_viewport->width()) / image.cols; // find the best value of zoom
double zoomY = double(ui->label_viewport->height()) / image.rows;
if (zoomX < zoomY) zoom = zoomX; // less = fit view borders