-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmainwindow.cpp
2171 lines (1806 loc) · 96.3 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
/*#-------------------------------------------------
#
# OpenCV Superpixels Segmentation
#
# by AbsurdePhoton - www.absurdephoton.fr
#
# v2.3 - 2019/07/08
#
#-------------------------------------------------*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QMouseEvent>
#include <QScrollBar>
#include <QCursor>
#include <QColorDialog>
#include <QWhatsThis>
//#include <opencv2/ximgproc.hpp>
#include <ImageMagick-7/Magick++.h>
#include "mat-image-tools.h"
using namespace cv;
using namespace cv::ximgproc;
using namespace std;
using namespace Magick;
/////////////////// Window init //////////////////////
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
// Populate combo lists
ui->comboBox_algorithm->blockSignals(true); // don't trigger the automatic actions for these widgets
ui->comboBox_algorithm->addItem(tr("SLIC")); // algorithms
ui->comboBox_algorithm->addItem(tr("SLICO"));
ui->comboBox_algorithm->addItem(tr("MSLIC"));
ui->comboBox_algorithm->addItem(tr("LSC"));
ui->comboBox_algorithm->addItem(tr("SEEDS"));
ui->comboBox_algorithm->blockSignals(false);
ui->comboBox_grid_color->blockSignals(true);
ui->comboBox_grid_color->addItem(tr("Red")); // grid colors
ui->comboBox_grid_color->addItem(tr("Green"));
ui->comboBox_grid_color->addItem(tr("Blue"));
ui->comboBox_grid_color->addItem(tr("Cyan"));
ui->comboBox_grid_color->addItem(tr("Magenta"));
ui->comboBox_grid_color->addItem(tr("Yellow"));
ui->comboBox_grid_color->addItem(tr("White"));
ui->comboBox_grid_color->blockSignals(false);
ui->comboBox_algorithm->setCurrentIndex(4); // SLIC
InitializeValues(); // init all indicators and zoom etc
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 base dir
}
else basedir = "/home/"; // base path and file
basefile = "";
}
MainWindow::~MainWindow()
{
delete ui;
}
/////////////////// GUI //////////////////////
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();
}
void MainWindow::on_button_whats_this_clicked() // What's this function
{
QWhatsThis::enterWhatsThisMode();
}
void MainWindow::on_Tabs_currentChanged(int) // when a tab is clicked
{
if(ui->Tabs->currentIndex()==2) ui->label_segmentation->setCursor(Qt::PointingHandCursor); // labels tab ? => labels view cursor
else ui->label_segmentation->setCursor(Qt::ArrowCursor); // default cursor
}
void MainWindow::InitializeValues() // initialize all sorts of indicators, zoom, etc
{
// Hide tabs
ui->Tabs->setTabEnabled(1, false);
ui->Tabs->setTabEnabled(2, false);
// Hide drawing tools
ui->frame_draw->setVisible(false);
// LCD
ui->lcd_cells->setPalette(Qt::red);
// Global variables init
loaded = false; // main image loaded ?
computed = false; // segmentation not yet computed
color = Vec3b(0,0,255); // pen color
gridColor = Vec3b(0, 0, 255); // current grid color
zoom = 1; // init zoom
oldZoom = 1; // to detect a zoom change
zoom_type = ""; // "button" or (mouse) "wheel"
// labels list
maxLabels = 0; // for new labels
ui->comboBox_grid_color->setCurrentIndex(0);
}
/////////////////// Labels //////////////////////
int MainWindow::GetCurrentLabelNumber() // label number for use with labels_mask
{
return ui->listWidget_labels->currentItem()->data(Qt::UserRole).toInt(); // label number stored in the special field
}
void MainWindow::DeleteAllLabels(bool newLabel) // add a label to the list
{
maxLabels = 0; // reset labels
ui->listWidget_labels->blockSignals(true); // the labels list must not trigger an action
ui->listWidget_labels->clear(); // delete all labels
ui->listWidget_labels->blockSignals(false); // return to normal
if (newLabel) AddNewLabel(""); // add one new default label or not
}
void MainWindow::UnselectAllLabels() // unselect all labels in list
{
for (int n = 0; n < ui->listWidget_labels->count(); n++) // for each label
ui->listWidget_labels->item(n)->setSelected(false); // unselect it
}
QListWidgetItem* MainWindow::AddNewLabel(QString newLabel) // add a label to the list
{
UnselectAllLabels(); // the new one will be the only selected
QListWidgetItem *item = new QListWidgetItem ();
if (newLabel == "") item->setText("Rename me!"); // default text of the label
else item->setText(newLabel); // or custom text
maxLabels++; // increase total number of labels
item->setData(Qt::UserRole, maxLabels); // custom field = label number
item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled); // item enabled, editable and selectable
item->setBackground(QColor(0, 0, 255)); // label color
if (IsRGBColorDark(0, 0, 255)) // is the label color dark ?
item->setForeground(QColor(255, 255, 255)); // if so light text color
else item->setForeground(QColor(0, 0, 0)); // if not dark text color
ui->listWidget_labels->addItem(item); // add the item to the list
ui->listWidget_labels->setCurrentItem(item); // select the new label
return item; // pointer to new item
}
void MainWindow::on_listWidget_labels_currentItemChanged(QListWidgetItem *currentItem) // show current label color
{
QBrush brush = currentItem->background(); // the label color is stored in the background color of the list
ShowCurrentColor(brush.color().red(), brush.color().green(), brush.color().blue()); // show current color used
}
void MainWindow::on_listWidget_labels_itemChanged(QListWidgetItem *currentItem) // show current label text
{
ui->label_color->setText(currentItem->text()); // show label name
}
void MainWindow::on_pushButton_label_add_clicked() // add new default label
{
if (!computed) { // if image not computed yet get out
QMessageBox::warning(this, "No cells found",
"Not now!\n\nBefore anything else, compute the segmentation or load a previous session");
return;
}
AddNewLabel("");
}
void MainWindow::on_pushButton_label_hide_clicked() // hide label = set its color to 0
{
if (!computed) { // if image not computed yet get out
QMessageBox::warning(this, "No cells found",
"Not now!\n\nBefore anything else, compute the segmentation or load a previous session");
return;
}
color = Vec3b(0,0,0); // black = transparent
ShowCurrentColor(color[2], color[1], color[0]); // set black color to label
}
void MainWindow::on_pushButton_label_delete_clicked() // delete the current label
{
if (!computed) { // if image not computed yet get out
QMessageBox::warning(this, "No cells found",
"Not now!\n\nBefore anything else, compute the segmentation or load a previous session");
return;
}
if (ui->listWidget_labels->count() == 1) { // last label ?
QMessageBox::warning(this, "Delete label", "You can't delete the last label in the list");
return;
}
QListWidgetItem *item = ui->listWidget_labels->currentItem();
int deletion = QMessageBox::question(this, "Delete label", "Are you sure?\n''" + item->text() + "'' label will be deleted", QMessageBox::Yes|QMessageBox::No); // sure ?
if (deletion == QMessageBox::No) // don't delete it !
return;
Mat1b superpixel_mask = labels_mask == GetCurrentLabelNumber(); // extract label to delete from labels mask
mask.setTo(0, superpixel_mask); // set 0 (= unclaimed) to labels mask
ShowSegmentation(); // display mask
int row = ui->listWidget_labels->currentRow(); // current label to delete
ui->listWidget_labels->removeItemWidget(item); // delete item object
ui->listWidget_labels->takeItem(row); // delete label from list
}
void MainWindow::on_pushButton_label_join_clicked() // join 2 or more labels, result to one selected label
{
int join = QMessageBox::question(this, "Join labels", "Are you sure?\n\nSelected labels in the list will be joined", QMessageBox::Yes|QMessageBox::No); // sure ?
if (join == QMessageBox::No) // join the mask !
return;
QList<QListWidgetItem *> items = ui->listWidget_labels->selectedItems(); // get selected items
if (items.count() < 2) // only one label selected ?
{
QMessageBox::warning(this, "Join labels",
"You have to select more than one label to join");
return;
}
QBrush brush = items[0]->background(); // color of first label encountered: this label will contain the result
Vec3b col = Vec3b(brush.color().red(), brush.color().green(), brush.color().blue()); // get its color
int id = items[0]->data(Qt::UserRole).toInt(); // and get its label number for labels mask
for (int i = 1; i < items.count(); i++) { // each item of the list minus the first
Mat1b superpixel_mask = labels_mask == items[i]->data(Qt::UserRole).toInt(); // label number for labels mask
labels_mask.setTo(id, superpixel_mask); // claim cells for the first label
mask.setTo(col, superpixel_mask); // and set its color to the mask
ui->listWidget_labels->setCurrentItem(items[i]); // select the item
int row = ui->listWidget_labels->currentRow(); // find its row number in the list
ui->listWidget_labels->removeItemWidget(items[i]); // delete this item
ui->listWidget_labels->takeItem(row); // and delete the label from the list
}
items[0]->setText(items[0]->text() + " (joined)"); // add "join" to the first label name containing the result
ShowSegmentation(); // show result
}
void MainWindow::on_pushButton_label_draw_clicked() // special mode to modify the cells (superpixels)
{
if (!computed) { // if image not computed yet get out
QMessageBox::warning(this, "No cells found",
"Not now!\n\nBefore anything else, compute the segmentation or load a previous session");
ui->pushButton_label_draw->setChecked(false); // get out of the special mode
return;
}
if (ui->pushButton_label_draw->isChecked()) { // initialize cell update
ui->label_segmentation->setCursor(Qt::CrossCursor); // cursor change to show this is a special mode
ui->frame_pick_colors->setVisible(false); // disable all tabs/elements to keep the user in the special mode
ui->pushButton_label_add->setVisible(false);
ui->pushButton_label_delete->setVisible(false);
ui->pushButton_label_hide->setVisible(false);
ui->pushButton_label_join->setVisible(false);
ui->button_load_session->setVisible(false);
ui->button_save_session->setVisible(false);
ui->pushButton_psd->setVisible(false);
ui->pushButton_tif->setVisible(false);
ui->button_quit->setVisible(false);
ui->frame_draw->setVisible(true);
ui->Tabs->setTabEnabled(0, false);
ui->Tabs->setTabEnabled(1, false);
ui->listWidget_labels->setEnabled(false);
ui->checkBox_mask->setChecked(true);
ui->pushButton_draw_grabcut_iteration->setVisible(false);
ui->checkBox_selection->setChecked(false);
mask.copyTo(draw_cell_mask_save); // save all the masks
labels_mask.copyTo(draw_cell_labels_mask_save);
labels.copyTo(draw_cell_labels_save);
grid.copyTo(draw_cell_grid_save);
pos_save = cv::Point(-1, -1); // no first line point defined
}
else { // special mode ended by clicking again the button
int draw = QMessageBox::question(this, "Update cells", "Are you sure you want to update the cells from the white mask?\nIf not, the mask will be deleted", QMessageBox::Yes|QMessageBox::No); // really update the cells ?
double min, max;
minMaxIdx(labels, &min, &max); // find the highest superpixel number
int maxLabel = max + 1; // superpixel value of new cell
Mat1b white_mask;
inRange(mask, Vec3b(255, 255, 255), Vec3b(255, 255, 255), white_mask); // extract white color from mask
if ((cv::sum(white_mask) != Scalar(0,0,0)) & (draw == QMessageBox::Yes)) { // update the cells
vector<vector<cv::Point>> contours;
vector<Vec4i> hierarchy;
findContours(white_mask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // find new cell contours
grid.setTo(0, white_mask); // erase cell in grid mask
drawContours(grid, contours, -1, gridColor, 1, 8, hierarchy ); // draw contour of new cell in grid
draw_cell_mask_save.copyTo(mask); // restore mask
labels.setTo(maxLabel, white_mask); // set new superpixel value in labels
labels_mask.setTo(GetCurrentLabelNumber(), white_mask); // set current label value in labels mask
mask.setTo(color, white_mask); // update mask with current label color
}
else // don't update the cells !
{
if ((cv::sum(white_mask) == Scalar(0,0,0)) & (draw == QMessageBox::Yes))
QMessageBox::warning(this, "Not updating the cells",
"The mask was empty, cells not updated");
draw_cell_mask_save.copyTo(mask); // restore original mask
ShowSegmentation(); // show view back to previous state
}
//SaveUndo(); // save current state
ui->label_segmentation->setCursor(Qt::PointingHandCursor); // cursor back to normal
ui->frame_pick_colors->setVisible(true); // show again the elements hidden for the special mode
ui->pushButton_label_add->setVisible(true);
ui->pushButton_label_delete->setVisible(true);
ui->pushButton_label_hide->setVisible(true);
ui->pushButton_label_join->setVisible(true);
ui->button_load_session->setVisible(true);
ui->button_save_session->setVisible(true);
ui->pushButton_psd->setVisible(true);
ui->pushButton_tif->setVisible(true);
ui->button_quit->setVisible(true);
ui->frame_draw->setVisible(false);
ui->Tabs->setTabEnabled(0, true);
ui->Tabs->setTabEnabled(1, true);
ui->listWidget_labels->setEnabled(true);
ui->checkBox_selection->setChecked(true);
ShowCurrentColor(color[2], color[1], color[0]); // redraw label
}
}
void MainWindow::on_pushButton_draw_clear_clicked() // clear the cell drawing mask
{
SaveUndo(); // save current state
draw_cell_mask_save.copyTo(mask); // Restore current mask
ShowSegmentation(); // show view back to previous state
}
void MainWindow::on_pushButton_draw_grabcut_clicked() // use GrabCut in cell drawing mode
{
SaveUndo(); // save current state
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
grabcut_mask = Mat::zeros(image.rows, image.cols, CV_8UC1);
grabcut_mask = GC_BGD; // init GrabCut with 'maybe Background'
grabcut_foreground.release(); // clear grabcut internal masks
grabcut_background.release();
Mat1b mask_tmp = Mat::zeros(image.rows, image.cols, CV_8UC1); // to find white, red or blue pixels
cv::inRange(mask, Vec3b(255,255,255), Vec3b(255,255,255), mask_tmp); // find white
grabcut_mask.setTo(GC_FGD, mask_tmp); // white = foreground
cv::inRange(mask, Vec3b(0,0,255), Vec3b(0,0,255), mask_tmp); // find red
grabcut_mask.setTo(GC_BGD, mask_tmp); // red = background
cv::inRange(mask, Vec3b(255,0,0), Vec3b(255,0,0), mask_tmp); // find blue
grabcut_mask.setTo(GC_PR_FGD, mask_tmp); // blue = maybe foreground
cv::grabCut(image, // input image
grabcut_mask, // segmentation result
cv::Rect(0,0,image.cols,image.rows), // rectangle containing foreground, not used here
grabcut_background, grabcut_foreground, // internal for GrabCut
1, // number of iterations = 1
cv::GC_INIT_WITH_MASK); // init with mask (not rectangle)
draw_cell_mask_save.copyTo(mask); // restore mask
cv::inRange(grabcut_mask, GC_FGD, GC_FGD, mask_tmp); // get 'sure' foreground pixels
mask.setTo(Vec3b(255,255,255), mask_tmp); // set foreground = white in mask
cv::inRange(grabcut_mask, GC_PR_FGD, GC_PR_FGD, mask_tmp); // get 'maybe' foreground pixels
mask.setTo(Vec3b(255,0,0), mask_tmp); // set maybe = blue in mask
QApplication::restoreOverrideCursor(); // Restore cursor
ui->pushButton_draw_grabcut_iteration->setVisible(true); // show the new iteration button
ShowSegmentation(); // show GrabCut result
}
void MainWindow::on_pushButton_draw_grabcut_iteration_clicked() // repeat GrabCut in cell drawing mode
{
Mat1b mask_tmp; // temp mask
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
cv::grabCut(image, // input image
grabcut_mask, // segmentation result
cv::Rect(0,0,image.cols,image.rows), // rectangle containing foreground, not used here
grabcut_background, grabcut_foreground, // internal for GrabCut
1, // number of iterations = 1
cv::GC_EVAL); // resume algorithm
draw_cell_mask_save.copyTo(mask); // restore mask
cv::inRange(grabcut_mask, GC_FGD, GC_FGD, mask_tmp); // get 'sure' foreground pixels
mask.setTo(Vec3b(255,255,255), mask_tmp); // set foreground = white in mask
cv::inRange(grabcut_mask, GC_PR_FGD, GC_PR_FGD, mask_tmp); // get 'maybe' foreground pixels
mask.setTo(Vec3b(255,0,0), mask_tmp); // set maybe = blue in mask
QApplication::restoreOverrideCursor(); // Restore cursor
ShowSegmentation(); // show GrabCut result
}
Vec3b MainWindow::DrawColor() // return drawing color in cell drawing mode
{
Vec3b draw_color;
if (ui->radioButton_draw_mask->isChecked()) draw_color = Vec3b(255, 255, 255); // white = keep
if (ui->radioButton_draw_reject->isChecked()) draw_color = Vec3b(0, 0, 255); // red = reject
if (ui->radioButton_draw_maybe->isChecked()) draw_color = Vec3b(255, 0, 0); // blue = maybe
return draw_color;
}
/////////////////// 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::on_pushButton_psd_clicked() // save image (background) + layers (labels) to PSD Photoshop image
{
SavePSDorTIF("psd");
}
void MainWindow::on_pushButton_tif_clicked() // save image + layers as pages to multipage TIFF image
{
SavePSDorTIF("tif");
}
Magick::Image Mat2Magick(const Mat &src) // image conversion from Mat to Magick (only for RGB images)
{
Magick::Image mgk(Geometry(src.cols, src.rows), "black"); // result image
mgk.read(src.cols, src.rows, "BGR", Magick::CharPixel, (char*)src.data); // transfer image data from Mat
return mgk;
}
void MainWindow::SavePSDorTIF(std::string type) // save image + layers to PSD or TIFF image
{
if (!loaded) { // if image not loaded yet get out
QMessageBox::warning(this, "Image not loaded",
"Not now!\n\nBefore anything else, load an image");
return;
}
std::string ext = type; // file type
std::transform(type.begin(), type.end(), type.begin(), ::toupper); // file type uppercase
QString filename = QFileDialog::getSaveFileName(this, "Save labels to multi-layers image file...", // choose filename
"./" + QString::fromStdString(basedir + basefile + "-segmentation-labels." + ext),
QString::fromStdString("*." + ext + " *." + type));
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
QApplication::setOverrideCursor(Qt::WaitCursor); // wait cursor
std::string fileImage = filename.toUtf8().constData(); // convert filename to std::string
if (type == "TIF") type = "TIFF"; // add a F to TIF
vector<Image> imageList; // layers (labels) list
Magick::Image bkg; // result
bkg = Mat2Magick(image); // convert image
bkg.magick(type); // set layer type to PSD or TIFF
if (type == "PSD") bkg.compressType(RLECompression); // RLE compression for PSD
else bkg.compressType(LZWCompression); // and LZW for TIFF
bkg.density(300); // dpi
bkg.resolutionUnits(PixelsPerInchResolution); // dpi unit
bkg.label("Background"); // for Photoshop image is the "background"
imageList.push_back(bkg); // add image to the list
if (type == "PSD") imageList.push_back(bkg); // for PSD the first image is the preview, the second is the background
int nb_count = ui->listWidget_labels->count(); // how many layerss (labels) to save ?
for (int i = 0; i < nb_count; i++) { // for each label
QListWidgetItem *item = ui->listWidget_labels->item(i); // this label from the list
int id = item->data(Qt::UserRole).toInt(); // get its label id for labels mask
//std::string name = std::to_string(i) + "-" + item->text().toUtf8().constData(); // unique label name
std::string name = item->text().toUtf8().constData(); // convert label name to std::string
QBrush brush = item->background(); // label color
Vec3b col = Vec3b(brush.color().red(), brush.color().green(), brush.color().blue());
Mat1b superpixel_mask = labels_mask == id; // extract label
Mat save; // current layer image
image.copyTo(save); // copy image structure
save = 0; // set it to 0 (transparent)
save.setTo(Vec3b(col[2], col[1], col[0]), superpixel_mask); // copy cells to layer
Magick::Image img(Geometry(image.cols, image.rows), "black"); // Magick current layer
img = Mat2Magick(save); // convert Mat layer to Magick layer
if (type == "TIFF") bkg.depth(8); // 8-bit TIFF
img.transparent(Magick::Color(0,0,0)); // set the transparent color
if (type == "PSD") img.compressType(RLECompression); // RLE compression for PSD
else img.compressType(LZWCompression); // and LZW for TIFF
img.label(name); // set the name (doesn't work for TIFF pages)
img.density(300); // dpi
img.resolutionUnits(PixelsPerInchResolution); // dpi unit
img.magick(type); // set PSD or TIFF type
imageList.push_back(img); // save the image to the list
}
Magick::writeImages(imageList.begin(), imageList.end(), fileImage, true); // Write result to disk
QApplication::restoreOverrideCursor(); // Restore cursor
}
void MainWindow::on_button_image_clicked() // Load main image
{
QString filename = QFileDialog::getOpenFileName(this, "Select picture file", QString::fromStdString(basedir),
tr("Images (*.jpg *.jpeg *.jp2 *.png *.tif *.tiff)")); // image filename
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
basefile = filename.toUtf8().constData(); // base file name and dir are used after to save other files
basefile = basefile.substr(0, basefile.size()-4); // strip the file extension
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
ui->label_filename->setText(filename); // display file name in ui
SaveDirBaseFile(); // Save current path to ini file
std::string filename_s = filename.toUtf8().constData(); // convert filename from QString
cv::Mat mat = cv::imread(filename_s, IMREAD_COLOR); // Load image
if (mat.empty()) { // problem ?
QMessageBox::critical(this, "File error",
"There was a problem reading the image file");
return;
}
ui->label_thumbnail->setPixmap(QPixmap()); // unset all images in GUI
ui->label_segmentation->setPixmap(QPixmap());
ui->label_thumbnail->setPixmap(Mat2QPixmapResized(mat, ui->label_thumbnail->width(), ui->label_thumbnail->height(), true)); // Show thumbnail
image = mat; // store the image for further use
mat.copyTo(image_backup); // for undo
selection = Mat::zeros(image.rows, image.cols, CV_8UC3); // init selection mask
ui->label_segmentation->setPixmap(QPixmap()); // Delete the depthmap image
ui->label_segmentation->setText("Segmentation not computed"); // Text in the segmentation area
ui->horizontalScrollBar_segmentation->setMaximum(0); // update scrollbars
ui->verticalScrollBar_segmentation->setMaximum(0);
ui->horizontalScrollBar_segmentation->setValue(0);
ui->verticalScrollBar_segmentation->setValue(0);
ui->lcd_cells->setPalette(Qt::red); // LCD count red = not yet computed
ui->lcd_cells->display(0); // LCD count
ui->label_image_width->setText(QString::number(image.cols)); // display image dimensions
ui->label_image_height->setText(QString::number(image.rows));
InitializeValues(); // reset all variables
double zoomX = double(ui->label_segmentation->width()) / image.cols; // try vertical and horizontal ratios
double zoomY = double(ui->label_segmentation->height()) / image.rows;
if (zoomX < zoomY) zoom = zoomX; // the lowest fit the view
else zoom = zoomY;
oldZoom = zoom; // for center view
ShowZoomValue(); // display current zoom
viewport = Rect(0, 0, image.cols, image.rows); // update viewport
cv::resize(image, thumbnail, Size(ui->label_thumbnail->pixmap()->width(),ui->label_thumbnail->pixmap()->height()),
0, 0, INTER_AREA); // create thumbnail
mask.release(); // reinit mask
grid.release(); // reinit grid
undo_mask.release(); // reinit undo masks
undo_labels.release();
selection.release();
loaded = true; // image loaded successfuly
computed = false; // segmentation not performed
DeleteAllLabels(true); // empty a previous labels list
SaveUndo(); // for undo
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_segmentation->setPixmap(D); // Set new image content to viewport
DisplayThumbnail(); // update thumbnail view
ShowSegmentation(); // show the result
ui->Tabs->setTabEnabled(1, true); // enable Segmentation and Labels tabs
ui->Tabs->setTabEnabled(2, true);
}
void MainWindow::on_button_save_session_clicked() // save session files
{
if (!computed) { // if image not computed yet get out
QMessageBox::warning(this, "No cells found",
"Not now!\n\nBefore anything else, compute the segmentation or load a previous session");
return;
}
QString filename = QFileDialog::getSaveFileName(this, "Save session to XML file...", "./" + QString::fromStdString(basedir + basefile + "-segmentation-data.xml"), tr("XML (*.xml)")); // filename
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
std::string filesession = filename.toUtf8().constData(); // base file name
size_t pos = filesession.find("-segmentation-data.xml");
if (pos != std::string::npos) filesession.erase(pos, filesession.length());
pos = filesession.find(".xml");
if (pos != std::string::npos) filesession.erase(pos, filesession.length());
bool write;
write = cv::imwrite(filesession + "-segmentation-mask.png", mask); // save mask
if (!write) {
QMessageBox::critical(this, "File error",
"There was a problem saving the segmentation mask image file");
return;
}
write = cv::imwrite(filesession + "-segmentation-grid.png", grid); // save grid
if (!write) {
QMessageBox::critical(this, "File error",
"There was a problem saving the segmentation grid image file");
return;
}
write = cv::imwrite(filesession + "-segmentation-image.png", image); // save processed image
if (!write) {
QMessageBox::critical(this, "File error",
"There was a problem saving the segmentation image file");
return;
}
cv::FileStorage fs(filesession + "-segmentation-data.xml", cv::FileStorage::WRITE); // open labels file for writing
if (!fs.isOpened()) {
QMessageBox::critical(this, "File error",
"There was a problem writing the segmentation data file");
return;
}
int gridValue = ui->comboBox_grid_color->currentIndex(); // save grid color
fs << "GridColor" << gridValue; // write labels count
int nb_count = ui->listWidget_labels->count(); // how many labels to save ?
fs << "LabelsCount" << nb_count; // write labels count
for (int i = 0; i < nb_count; i++) { // for each label
std::string field;
QListWidgetItem *item = ui->listWidget_labels->item(i); // 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;
QBrush brush = item->background(); // write label color
Vec3b col = Vec3b(brush.color().red(), brush.color().green(), brush.color().blue());
field = "LabelColor" + std::to_string(i);
fs << field << col;
}
fs << "Labels" << labels; // write labels Mat
fs << "LabelsMask" << labels_mask; // write labels mask Mat
fs.release(); // close file
QMessageBox::information(this, "Save segmentation session", "Session saved with base name:\n" + QString::fromStdString(filesession));
basefile = filesession; // base file name and dir are used after to save other files
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
pos = basefile.find("-segmentation-data");
if (pos != std::string::npos) basefile.erase(pos, basefile.length());
ui->label_filename->setText(filename); // display file name in ui
SaveDirBaseFile(); // Save current path to ini file
}
void MainWindow::on_button_load_session_clicked() // load previous session
{
//if (image.empty()) // image mandatory
// return;
QString filename = QFileDialog::getOpenFileName(this, "Load session from XML file...", QString::fromStdString(basedir), tr("XML (*.xml)"));
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
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
pos = basefile.find("-segmentation-data");
if (pos != std::string::npos) basefile.erase(pos, basefile.length());
ui->label_filename->setText(filename); // display file name in ui
SaveDirBaseFile(); // Save current path to ini file
std::string filesession = filename.toUtf8().constData(); // base file name
pos = filesession.find("-segmentation-data.xml");
if (pos != std::string::npos) filesession.erase(pos, filesession.length());
InitializeValues(); // reinit all variables
image.release();
mask.release();
grid.release();
mask = cv::imread(filesession + "-segmentation-mask.png", IMREAD_COLOR); // load mask
if (mask.empty()) {
QMessageBox::critical(this, "File error",
"There was a problem reading the segmentation mask file:\nit must end with ''-segmentation-mask.png''");
return;
}
grid = cv::imread(filesession + "-segmentation-grid.png"); // load grid
if (grid.empty()) {
QMessageBox::critical(this, "File error",
"There was a problem reading the segmentation grid file:\nit must end with ''-segmentation-grid.png''");
return;
}
image = cv::imread(filesession + "-segmentation-image.png"); // load processed 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''");
return;
}
DeleteAllLabels(false); // delete all labels but do not create a new one
cv::FileStorage fs(filesession + "-segmentation-data.xml", FileStorage::READ); // open labels file
if (!fs.isOpened()) {
QMessageBox::critical(this, "File error",
"There was a problem reading the segmentation data file:\nit must end with ''-segmentation-data.xml''");
return;
}
Mat labels_temp(image.rows, image.cols, CV_32SC1);
fs["Labels"] >> labels_temp; // load labels
labels_temp.copyTo(labels);
fs["LabelsMask"] >> labels_temp; // load labels mask
labels_temp.copyTo(labels_mask);
maxLabels = 0; // reset label count
int nb_count, gridValue;
fs["GridColor"] >> gridValue; // grid color
fs["LabelsCount"] >> nb_count; // read how many labels to load ?
for (int i = 0; i < nb_count; i++) { // for each label to load
QListWidgetItem *item = new QListWidgetItem (); // create new label
std::string field;
int num;
field = "LabelId" + std::to_string(i); // read label id
fs [field] >> num;
item->setData(Qt::UserRole, num); // set it to current label
if (num > maxLabels) maxLabels = num; // numLabels must be equal to the max label value
std::string name;
field = "LabelName" + std::to_string(i); // read label name
fs [field] >> name;
item->setText(QString::fromStdString(name)); // set name to current label
Vec3b col;
field = "LabelColor" + std::to_string(i); // read label color
fs [field] >> col;
item->setBackground(QColor(col[0], col[1], col[2])); // set color to current label
if (IsRGBColorDark(col[0], col[1], col[2])) // set text color relative to background darkness
item->setForeground(QColor(255, 255, 255));
else item->setForeground(QColor(0, 0, 0));
item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled); // item enabled, editable and selectable
ui->listWidget_labels->addItem(item); // add the new item to the list
ui->listWidget_labels->setCurrentItem(item); // select the new label
item->setSelected(false); // don't select it !
ui->Tabs->setTabEnabled(1, true); // enable Segmentation and Labels tabs
ui->Tabs->setTabEnabled(2, true);
ui->Tabs->setCurrentIndex(2);
}
fs.release(); // close file
ui->label_thumbnail->setPixmap(QPixmap()); // reinit all images in GUI
ui->label_segmentation->setPixmap(QPixmap());
ui->label_thumbnail->setPixmap(Mat2QPixmapResized(image, ui->label_thumbnail->width(), ui->label_thumbnail->height(), true)); // Show thumbnail
double zoomX = double(ui->label_segmentation->width()) / image.cols; // try vertical and horizontal ratios
double zoomY = double(ui->label_segmentation->height()) / image.rows;
if (zoomX < zoomY) zoom = zoomX; // the lowest fit the view
else zoom = zoomY;
oldZoom = zoom; // for center view
ShowZoomValue(); // display current zoom
viewport = Rect(0, 0, image.cols, image.rows); // update viewport
cv::resize(image, thumbnail, Size(ui->label_thumbnail->pixmap()->width(),ui->label_thumbnail->pixmap()->height()),
0, 0, INTER_AREA); // create thumbnail
undo_mask.release(); // reinit undo masks
undo_labels.release();
selection.release();
image.copyTo(image_backup); // for undo
selection = Mat::zeros(image.rows, image.cols, CV_8UC3);
double min, max;
minMaxIdx(labels, &min, &max); // find the highest superpixel number
ui->lcd_cells->setPalette(Qt::red); // LCD count red = not yet computed
ui->lcd_cells->display(max); // LCD count
ui->label_image_width->setText(QString::number(image.cols)); // display image dimensions
ui->label_image_height->setText(QString::number(image.rows));
SaveUndo(); // for undo
loaded = true; // done !
computed = true; // not really computed but necessary
ui->comboBox_grid_color->setCurrentIndex(gridValue); // update grid color in ui
UnselectAllLabels(); // only the first label must be selected
ui->listWidget_labels->setCurrentRow(0);
//QMessageBox::information(this, "Load segmentation session", "Session loaded with base name:\n" + QString::fromStdString(filesession));
}
void MainWindow::on_button_save_conf_clicked() // save configuration
{
QString filename = QFileDialog::getSaveFileName(this, "Save configuration to XML file...", "./" + QString::fromStdString(basedir + basefile + "-segmentation-conf.xml"), tr("XML (*.xml)"));
if (filename.isNull() || filename.isEmpty()) // cancel ?
return;
std::string filename_s = filename.toUtf8().constData(); // Convert from QString
int algorithm = ui->comboBox_algorithm->currentIndex(); // Initialize variables to save from GUI
int region_size = ui->horizontalSlider_region_size->value();
int ruler = ui->horizontalSlider_ruler->value();
int min_element_size = ui->horizontalSlider_connectivity->value();
int num_iterations = ui->horizontalSlider_iterations->value();
int line_color = ui->comboBox_grid_color->currentIndex();
bool thick_lines = ui->checkBox_thick->isChecked();
int num_superpixels = ui->horizontalSlider_num_superpixels->value();
int num_levels = ui->horizontalSlider_num_levels->value();
int prior = ui->horizontalSlider_prior->value();
int num_histogram_bins = ui->horizontalSlider_num_histogram_bins->value();
bool double_step = ui->checkBox_double_step->isChecked();
double ratio = ui->doubleSpinBox_ratio->value();
bool lab = ui->checkBox_lab_colors->isChecked();
bool gaussian_blur = ui->checkBox_gaussian_blur->isChecked();
bool normalize = ui->checkBox_normalize->isChecked();
bool equalize = ui->checkBox_equalize->isChecked();
bool color_balance = ui->checkBox_color_balance->isChecked();
int color_balance_percent = ui->spinBox_color_balance_percent->value();
bool contours = ui->checkBox_contours->isChecked();
int contours_sigma = ui->spinBox_contours_sigma->value();
int contours_thickness = ui->spinBox_contours_thickness->value();
int contours_aperture = ui->comboBox_contours_aperture->currentIndex() * 2 + 3;
bool denoise = ui->checkBox_denoise->isChecked();
int luminance = ui->horizontalSlider_luminance->value();
int chrominance = ui->horizontalSlider_chrominance->value();
FileStorage fs(filename_s, FileStorage::WRITE); // save to openCV XML file type
if (!fs.isOpened()) {
QMessageBox::critical(this, "File error",
"There was a problem writing the configuration file");
return;
}
//// Segmentation parameters
fs << "Algorithm" << algorithm;
fs << "RegionSize" << region_size;
fs << "Ruler" << ruler;
fs << "Connectivity" << min_element_size;
fs << "NumIterations" << num_iterations;
fs << "Superpixels" << num_superpixels;
fs << "Levels" << num_levels;
fs << "Prior" << prior;
fs << "Histograms" << num_histogram_bins;
fs << "DoubleStep" << double_step;
fs << "Ratio" << ratio;
fs << "ThickLines" << thick_lines;
fs << "LabColors" << lab;
fs << "Color" << line_color;
//// image pre-production parameters
fs << "ColorBalance" << color_balance;
fs << "ColorBalancePercent" << color_balance_percent;
fs << "GaussianBlur" << gaussian_blur;
fs << "Normalize" << normalize;
fs << "Equalize" << equalize;
fs << "Contours" << contours;
fs << "ContoursSigma" << contours_sigma;
fs << "ContoursThickness" << contours_thickness;
fs << "ContoursAperture" << contours_aperture;
fs << "Noise" << denoise;
fs << "NoiseLuminance" << luminance;
fs << "NoiseChrominance" << chrominance;
fs.release(); // close file
QMessageBox::information(this, "Save configuration", "Configuration saved to:\n" + filename);
}
void MainWindow::on_button_load_conf_clicked() // load configuration
{
QString filename = QFileDialog::getOpenFileName(this, "Select XML configuration file", QString::fromStdString(basedir + basefile + "-segmentation-conf.xml"), tr("XML (*.xml)")); // filename
if (filename.isNull()) // cancel ?
return;
std::string filename_s = filename.toUtf8().constData(); // convert filename from QString to std::string
// Initialize variables to save
int algorithm, region_size, ruler, min_element_size, num_iterations, line_color, color_balance_percent,
num_superpixels, num_levels, prior, num_histogram_bins,
contours_sigma, contours_thickness, contours_aperture, luminance, chrominance;
double ratio;
bool thick_lines, double_step, lab, gaussian_blur, equalize, normalize, color_balance, contours, denoise;
FileStorage fs(filename_s, FileStorage::READ); // load from openCV XML file
if (!fs.isOpened()) {
QMessageBox::critical(this, "File error",
"There was a problem reading the configuration file");
return;
}
fs["Algorithm"] >> algorithm;
fs["RegionSize"] >> region_size;
fs["Ruler"] >> ruler;
fs["Connectivity"] >> min_element_size;
fs["NumIterations"] >> num_iterations;
fs["Superpixels"] >> num_superpixels;
fs["Levels"] >> num_levels;
fs["Prior"] >> prior;
fs["Histograms"] >> num_histogram_bins;
fs["DoubleStep"] >> double_step;
fs["Ratio"] >> ratio;
fs["ThickLines"] >> thick_lines;
fs["LabColors"] >> lab;
fs["Color"] >> line_color;
fs["ColorBalance"] >> color_balance;
fs["ColorBalancePercent"] >> color_balance_percent;
fs["GaussianBlur"] >> gaussian_blur;
fs["Normalize"] >> normalize;
fs["Equalize"] >> equalize;
fs["Contours"] >> contours;
fs["ContoursSigma"] >> contours_sigma;
fs["ContoursThickness"] >> contours_thickness;
fs["ContoursAperture"] >> contours_aperture;
fs["Noise"] >> denoise;
fs["NoiseLuminance"] >> luminance;
fs["NoiseChrominance"] >> chrominance;
fs.release();