-
Notifications
You must be signed in to change notification settings - Fork 0
/
annotatorwnd.cpp
2094 lines (1578 loc) · 67.1 KB
/
annotatorwnd.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
#include "annotatorwnd.h"
#include "ui_annotatorwnd.h"
#include <QPixmap>
#include <QImage>
#include <QWheelEvent>
#include <QTimer>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QSettings>
#include <QLibrary>
#include "textinfodialog.h"
#include "MiscUtils.h"
#include "FijiHelper.h"
#include "SuperVoxeler.h"
#include "regionlistframe.h"
#include "RegionGrowing.h"
#include "PluginBase.h"
#include <QColorDialog>
#include <QInputDialog>
#include <QThread>
#include "extras/waitform.h"
#include "preferencesdialog.h"
/** ---- these variables here are a bit dirty, but it is to avoid putting them in the .h file
** even though it prevents multiple instances
*/
static SuperVoxeler<unsigned char> mSVoxel;
/** Supervoxel selection **/
struct SupervoxelSelection
{
bool valid; // if it contains valid selection information
unsigned int svIdx; // supervoxel ID
SlicMapType::value_type pixelList; // pixels that are inside the selected supervoxel
} static mSelectedSV ;
static Region3D mSVRegion;
// this holds a pointer to the regionListFrame window (if there is one)
// and other info
struct
{
RegionListFrame *pFrame;
Matrix3D<unsigned int> lblMatrix;
unsigned int lblCount;
std::vector<ShapeStatistics<> > shapeInfo;
Region3D region3D; // region used at computation time, to convert back to whole image coordinate sytem
SlicMapType labelToPixelMap; // to speed up processing
} static mLabelListData;
static std::vector<PluginBase *> mPluginBaseList;
static PluginServicesList mPluginServList;
static std::vector<QLibrary *> mPluginLibList; // to free them before exiting
// list of overlay volumes, we use ptrs because it has no copy xtor
std::vector< Matrix3D<OverlayType> * > mOverlayVolumeList;
std::vector<QAction *> mOverlayMenuActions;
std::vector<QMenu *> mOverlayMenus; // choose color menu action
/** -------- Class begin ------------ **/
AnnotatorWnd::AnnotatorWnd(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::AnnotatorWnd)
{
ui->setupUi(this);
mLabelListData.pFrame = 0;
mSaveLabelsOnExit = false;
mConstraintsDisplayTimer = new QTimer(this);
connect( ui->groupBoxRestrictPixLabels, SIGNAL(toggled(bool)), this, SLOT(constraintsChangedCallback()) );
connect( ui->spinPixMax, SIGNAL(valueChanged(int)), this, SLOT(constraintsChangedCallback(int)) );
connect( ui->spinPixMin, SIGNAL(valueChanged(int)), this, SLOT(constraintsChangedCallback(int)) );
connect( mConstraintsDisplayTimer, SIGNAL(timeout()), this, SLOT(constraintsTimerCallback()) );
connect( ui->cubeBrushSizeX, SIGNAL(valueChanged(int)), this, SLOT(on_cubeBrushSizeX_valueChanged(int)) );
connect( ui->cubeBrushSizeY, SIGNAL(valueChanged(int)), this, SLOT(on_cubeBrushSizeY_valueChanged(int)) );
connect( ui->cubeBrushSizeZ, SIGNAL(valueChanged(int)), this, SLOT(on_cubeBrushSizeZ_valueChanged(int)) );
// settings
m_sSettingsFile = QApplication::applicationDirPath() + "/settings.ini";
qDebug() << m_sSettingsFile;
loadSettings();
mFileTypeFilter = "TIF (*.tif *.tiff)";
mScoreImageEnabled = false;
mSelectedSV.valid = false; // no valid selection so far
ui->centralWidget->setLayout( ui->horizontalLayout );
qDebug("Args: %d", (int)qApp->arguments().size());
for (unsigned i=0; i < qApp->arguments().size(); i++)
qDebug("Arg %d: %s", i, qApp->arguments()[i].toStdString().c_str());
// ask user to open raw file
std::string stdFName;
if (qApp->arguments().size() >= 2 && QFileInfo( qApp->arguments().at(1) ).exists())
stdFName = qApp->arguments().at(1).toStdString();
if (stdFName.empty())
{
QString fileName = QFileDialog::getOpenFileName( 0, "Load image", mSettingsData.loadPathVolume, mFileTypeFilter );
if (fileName.isEmpty()) {
QTimer::singleShot(1, qApp, SLOT(quit()));
return;
}
stdFName = fileName.toLocal8Bit().constData();
mSettingsData.loadPathVolume = QFileInfo( QString::fromStdString( stdFName) ).absolutePath();
}
try {
mVolumeData.load( stdFName );
} catch (std::exception &e)
{
QMessageBox::critical( this, "Cannot open image file", "Could not open the specified image, quitting.." );
QTimer::singleShot(1, qApp, SLOT(quit()));
return;
}
this->saveSettings();
// allocate label volume (per pixel)
mVolumeLabels.reallocSizeLike( mVolumeData );
mVolumeLabels.fill(0);
/** Parse remaining possible args **/
if (qApp->arguments().size() >= 3)
{
if ( loadAnnotation( qApp->arguments().at(2) ) )
{
if ( qApp->arguments().size() >= 5 && (qApp->arguments().at(4) == "yes") )
{
mSaveLabelsOnExit = true;
mSaveLabelsOnExitPath = qApp->arguments().at(2);
}
}
}
mCurZSlice = 0;
if (qApp->arguments().size() >= 4) {
bool ok = false;
unsigned int z = qApp->arguments().at(3).toUInt(&ok);
if (ok)
mCurZSlice = z;
}
//Brushes
cubeBrush.setSize(ui->cubeBrushSizeX->value(),ui->cubeBrushSizeY->value(),ui->cubeBrushSizeZ->value());
sphereBrush.setSize(ui->cubeBrushSizeX->value(),ui->cubeBrushSizeY->value(),ui->cubeBrushSizeZ->value());
//mVolumeData.load( "/data/phd/synapses/Rat/layer2_3stak_red_reg_z1.5_example_cropped.tif" );
//mVolumeData.load( "/data/phd/synapses/Rat/layer2_3stak_red_reg_z1.5_firstquarter.tif" );
//mVolumeData.load( "/data/phd/synapses/Rat/layer2_3stak_red_reg_z1.5.tif" );
//mVolumeData.save("/tmp/test.tif" );
//mVolumeData.load("/data/phd/twoexamples/00147.tif");
qDebug("Volume size: %dx%dx%d\n", mVolumeData.width(), mVolumeData.height(), mVolumeData.depth());
ui->zSlider->setMinimum(0);
ui->zSlider->setMaximum( mVolumeData.depth()-1 );
ui->zSlider->setSingleStep(1);
ui->zSlider->setPageStep(10);
ui->zSlider->setValue( mCurZSlice );
updateImageSlice();
// events
connect(ui->labelImg,SIGNAL(wheelEventSignal(QWheelEvent*)),this,SLOT(labelImageWheelEvent(QWheelEvent*)));
connect(ui->labelImg,SIGNAL(mouseMoveEventSignal(QMouseEvent*)),this,SLOT(labelImageMouseMoveEvent(QMouseEvent*)));
connect(ui->labelImg,SIGNAL(mouseReleaseEventSignal(QMouseEvent*)),this,SLOT(labelImageMouseReleaseEvent(QMouseEvent*)));
ui->labelImg->setMouseTracking(true);
connect(ui->zSlider,SIGNAL(sliderMoved(int)),this,SLOT(zSliderMoved(int)));
connect(ui->zSlider,SIGNAL(valueChanged(int)),this,SLOT(zSliderMoved(int)));
connect( ui->actionZoom_fit, SIGNAL(triggered()), ui->labelImg, SLOT(zoomFit()) );
connect( ui->actionOverlay_labels, SIGNAL(triggered()), this, SLOT(actionLabelOverlayTriggered()) );
connect( ui->actionSave_annotation, SIGNAL(triggered()), this, SLOT(actionSaveAnnotTriggered()) );
connect( ui->actionLoad_annotation, SIGNAL(triggered()), this, SLOT(actionLoadAnnotTriggered()) );
connect( ui->actionImport_annotation, SIGNAL(triggered()), this, SLOT(actionImportAnnotTriggered()) );
connect( ui->actionScoreImageLoad, SIGNAL(triggered()), this, SLOT(actionLoadScoreImageTriggered()) );
connect( ui->actionScoreImageEnabled, SIGNAL(triggered()), this, SLOT(actionEnableScoreImageTriggered()) );
connect(ui->chkLabelOverlay,SIGNAL(stateChanged(int)),this,SLOT(chkLabelOverlayStateChanged(int)));
connect(ui->dialLabelOverlayTransp,SIGNAL(valueChanged(int)),this,SLOT(dialOverlayTransparencyMoved(int)));
//connect(ui->butGenSV, SIGNAL(clicked()), this, SLOT(genSupervoxelClicked()));
// ---- Create supervoxel menu
QMenu *testMenu = new QMenu(this);
connect( testMenu->addAction("Local (current view)"), SIGNAL(triggered()), this, SLOT(genSupervoxelClicked()) );
connect( testMenu->addAction("Global"), SIGNAL(triggered()), this, SLOT(genSuperVoxelWholeVolumeClicked()) );
connect( testMenu->addAction("Save global to file..."), SIGNAL(triggered()), this, SLOT(saveSuperVoxelWholeVolumeClicked()) );
connect( testMenu->addAction("Load global from file..."), SIGNAL(triggered()), this, SLOT(loadSuperVoxelWholeVolumeClicked()) );
ui->butGenSV->setMenu(testMenu);
connect( ui->butConnectivityRun, SIGNAL(clicked()), this, SLOT(butRunConnectivityCheckNowClicked()) );
connect(ui->butAnnotVis3D, SIGNAL(clicked()), this, SLOT(annotVis3DClicked()));
connect( ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferencesDialog()) );
connect( ui->spinScoreThrAbove, SIGNAL(valueChanged(int)), this, SLOT(updateImageSlice(int)) );
connect( ui->spinScoreThrBelow, SIGNAL(valueChanged(int)), this, SLOT(updateImageSlice(int)) );
connect( ui->actionHide_volume, SIGNAL(changed()), this, SLOT(updateImageSlice()) );
ui->chkLabelOverlay->setChecked(true);
//TODO the row is changed before triggering the slot so this does not work
connect( ui->layersDisplay, SIGNAL(currentRowChanged(int)), this, SLOT(selectedOverlayChanged(int)));
mOverlayLabelImage = ui->chkLabelOverlay->checkState() == Qt::Checked;
//Label combobox
fillLabelComboBox(3);
dialOverlayTransparencyMoved( 0 );
updateImageSlice();
// add as many overlay volumes (initially empty) as needed
{
ui->menuView->addSeparator();
//Save active overlay
QAction *save = ui->menuView->addAction("Save active overlay");
//TODO check if that's the proper way to assign the key
save->setShortcut( QKeySequence( QString("S") ) );
connect( save, SIGNAL(triggered()), this, SLOT(overlaySaveTriggered()) );
//Reload active overlay
QAction *reload = ui->menuView->addAction("Reload active overlay");
reload->setShortcut( QKeySequence( QString("R") ) );
connect( reload, SIGNAL(triggered()), this, SLOT(overlayReloadTriggered()) );
// create objects + add overlay visibility menus/shortcuts
for (int i=0; i < (int)PluginServices::getMaxOverlayVolumes(); i++ )
{
mOverlayVolumeList.push_back( new Matrix3D<OverlayType>() );
mOverlayInfo.push_back( new Overlay() );
QString name = QString("Overlay %1").arg(i+1);
ui->layersDisplay->addItem(name);
// add group for each one
QMenu *subMenu = ui->menuView->addMenu( mOverlayColorList.getIcon(i), name );
mOverlayMenus.push_back(subMenu);
// enable check box
QAction *selectOverlay = subMenu->addAction( "Select " + name );
selectOverlay->setShortcut( QKeySequence( QString("Ctrl+%1").arg(i+1) ) );
selectOverlay->setData( i ); // use data as index
connect( selectOverlay, SIGNAL(triggered()), this, SLOT(selectOverlay()) );
QAction *a = subMenu->addAction( "Enable " + name );
a->setCheckable(true);
a->setChecked(false);
a->setEnabled(false);
//a->setShortcut( QKeySequence( QString("%1").arg(i+1) ) );
connect( a, SIGNAL(triggered()), this, SLOT(updateImageSlice()) );
mOverlayMenuActions.push_back( a );
// add color chooser
QAction *aColor = subMenu->addAction( "Choose color..." );
aColor->setEnabled(true);
connect( aColor, SIGNAL(triggered()), this, SLOT(overlayChooseColorTriggered()) );
// add button to rescale overlay
QAction *rescale = subMenu->addAction("Rescale...");
rescale->setCheckable(false);
rescale->setEnabled(true);
rescale->setData( i ); // use data as index
connect( rescale, SIGNAL(triggered()), this, SLOT(overlayRescaleTriggered()) );
// and a load button too
QAction *load = subMenu->addAction("Load from file...");
load->setCheckable(false);
load->setEnabled(true);
load->setData( i ); // use data as index
connect( load, SIGNAL(triggered()), this, SLOT(overlayLoadTriggered()) );
// and a save button too
QAction *saveAs = subMenu->addAction("Save to file...");
saveAs->setCheckable(false);
saveAs->setEnabled(true);
saveAs->setData( i ); // use data as index
connect( saveAs, SIGNAL(triggered()), this, SLOT(overlaySaveAsTriggered()) );
}
}
//TODO this default transparency is hardcoded
mOverlayInfo[0]->alpha = 0.80;
mOverlayInfo[1]->alpha = 0.40;
//TODO assuming there will always be at least one overlay
ui->layersDisplay->setCurrentRow(0);
scanPlugins( qApp->applicationDirPath() + "/plugins/" );
//TODO allow them to be unhidden
ui->groupBoxRestrictPixLabels->hide();
ui->groupBoxSupervoxels->hide();
this->showMaximized();
}
void AnnotatorWnd::showPreferencesDialog()
{
PreferencesDialog dialog(this);
dialog.setFijiExePath( mSettingsData.fijiExePath );
dialog.setMaxVoxelsForSV( mSettingsData.maxVoxForSVox );
if (dialog.exec() == QDialog::Rejected)
return;
mSettingsData.fijiExePath = dialog.getFijiExePath();
mSettingsData.maxVoxForSVox = dialog.getMaxVoxelsForSV();
mSettingsData.sliceJump = dialog.getSliceJump();
this->saveSettings();
}
void AnnotatorWnd::overlayChooseColorTriggered()
{
QAction *action = qobject_cast<QAction *>(sender());
int idx = action->data().toInt();
QColor c = QColorDialog::getColor( mOverlayColorList.getColor(idx), this );
if (!c.isValid()) return;
mOverlayColorList.replaceColor( idx, c );
mOverlayMenus.at(idx)->setIcon( mOverlayColorList.getIcon(idx) );
updateImageSlice();
}
void AnnotatorWnd::selectPaintingLabel()
{
QAction *action = qobject_cast<QAction *>(sender());
int idx = action->data().toInt();
ui->comboLabel->setCurrentIndex(idx);
}
void AnnotatorWnd::selectOverlay()
{
QAction *action = qobject_cast<QAction *>(sender());
int idx = action->data().toInt();
int debugRow = ui->layersDisplay->currentRow();
if(ui->layersDisplay->currentRow() != idx){
ui->layersDisplay->setCurrentRow(idx);
setOverlayVisible(idx, true);
}else
setOverlayVisible(idx,!mOverlayMenuActions[idx]->isEnabled());
ui->dialLabelOverlayTransp->setValue(mOverlayInfo[idx]->alpha*100);
}
void AnnotatorWnd::selectedOverlayChanged(int idx)
{
int debugRow = ui->layersDisplay->currentRow();
ui->layersDisplay->setCurrentRow(idx);
setOverlayVisible(idx, true);
ui->dialLabelOverlayTransp->setValue(mOverlayInfo[idx]->alpha*100);
}
void AnnotatorWnd::overlayLoadTriggered()
{
QAction *action = qobject_cast<QAction *>(sender());
int idx = action->data().toInt();
QString fileName = QFileDialog::getOpenFileName( this, "Load overlay image", mSettingsData.loadPathScores, mFileTypeFilter );
if (fileName.isEmpty())
return;
qDebug() << fileName;
std::string stdFName = fileName.toLocal8Bit().constData();
if (!mOverlayVolumeList[idx]->load( stdFName ))
QMessageBox::critical(this, "Cannot open file", QString("%1 could not be read.").arg(fileName));
if ( !mOverlayVolumeList[idx]->isSizeLike( mVolumeData ) )
{
QMessageBox::critical(this, "Dimensions do not match", "Image does not match original volume dimensions. Disabling this overlay.");
mOverlayMenuActions[idx]->setChecked(false);
mOverlayMenuActions[idx]->setEnabled(false);
updateImageSlice();
return;
}
// enable and show ;)
mOverlayMenuActions[idx]->setChecked(true);
mOverlayMenuActions[idx]->setEnabled(true);
updateImageSlice();
statusBarMsg("Overlay image loaded successfully.");
mSettingsData.loadPathScores = QFileInfo(fileName).absolutePath();
mSettingsData.saveFileInfoScores = QFileInfo(fileName);
this->saveSettings();
}
void AnnotatorWnd::overlayReloadTriggered()
{
int idx = ui->layersDisplay->currentIndex().row();
if(!mSettingsData.saveFileInfoScores.exists()){
QMessageBox::critical(this, "Cannot open file", QString("FileInfo is not set"));
return;
}
//TODO move this to another function called by both triggers
//TODO handle errors correctly of empty saveFileInfos here
QString fileName(mSettingsData.saveFileInfoScores.absolutePath() + "/"
+ mSettingsData.saveFileInfoScores.baseName() + "."
+ mSettingsData.saveFileInfoScores.completeSuffix());
std::string stdFName = fileName.toLocal8Bit().constData();
if (!mOverlayVolumeList[idx]->load( stdFName )){
QMessageBox::critical(this, "Cannot open file", QString("%1 could not be read.").arg(fileName));
return;
}
if ( !mOverlayVolumeList[idx]->isSizeLike( mVolumeData ) )
{
QMessageBox::critical(this, "Dimensions do not match", "Image does not match original volume dimensions. Disabling this overlay.");
mOverlayMenuActions[idx]->setChecked(false);
mOverlayMenuActions[idx]->setEnabled(false);
updateImageSlice();
return;
}
// enable and show ;)
mOverlayMenuActions[idx]->setChecked(true);
mOverlayMenuActions[idx]->setEnabled(true);
updateImageSlice();
statusBarMsg("Overlay image loaded successfully.");
mSettingsData.loadPathScores = QFileInfo(fileName).absolutePath();
mSettingsData.saveFileInfoScores = QFileInfo(fileName);
this->saveSettings();
}
void AnnotatorWnd::overlaySaveAsTriggered()
{
QAction *action = qobject_cast<QAction *>(sender());
int idx = action->data().toInt();
QString fileName = QFileDialog::getSaveFileName( this, "Save overlay image", mSettingsData.savePathScores, mFileTypeFilter );
if (fileName.isEmpty()){
//TODO say something!
qDebug() << "FileName is empty";
return;
}
if (!fileName.endsWith(".tif"))
fileName += ".tif";
qDebug() << fileName;
overlaySave(mOverlayVolumeList[idx],fileName);
mSettingsData.savePathScores = QFileInfo(fileName).absolutePath();
mSettingsData.saveFileInfoScores = QFileInfo(fileName);
this->saveSettings();
}
void AnnotatorWnd::overlaySaveTriggered()
{
//TODO is saving the selected layer ok?
int idx = ui->layersDisplay->currentIndex().row();
if(idx < 0 || idx > ui->layersDisplay->count()){
qDebug() << " unselected layer";
QMessageBox::critical(this, "Cannot open file", QString("Select a layer first"));
return;
}
Matrix3D<OverlayType> *overlay = mOverlayVolumeList.at(idx);
if(overlay == NULL || overlay->isEmpty()){
qDebug() << " overlay empty";
QMessageBox::critical(this, "Cannot open file", QString("Overlay is empty"));
return;
}
if(!mSettingsData.saveFileInfoScores.exists()){
qDebug() << "FileInfo does not exist";
//TODO put this somewhere else
QString fileName = QFileDialog::getSaveFileName( this, "Save overlay image", mSettingsData.savePathScores, mFileTypeFilter );
if (fileName.isEmpty()){
qDebug() << "FileName is empty";
return;
}
if (!fileName.endsWith(".tif"))
fileName += ".tif";
qDebug() << fileName;
overlaySave(mOverlayVolumeList[idx],fileName);
mSettingsData.savePathScores = QFileInfo(fileName).absolutePath();
mSettingsData.saveFileInfoScores = QFileInfo(fileName);
this->saveSettings();
return;
}
overlaySave(overlay, mSettingsData.saveFileInfoScores.absolutePath() + "/"
+ mSettingsData.saveFileInfoScores.baseName() + "."
+ mSettingsData.saveFileInfoScores.completeSuffix());
}
void AnnotatorWnd::overlaySave(Matrix3D<OverlayType> *overlay, QString filePath)
{
std::string stdFName = filePath.toLocal8Bit().constData();
if (!overlay->save( stdFName )) {
statusBarMsg(QString("Error saving ") + filePath, 0 );
return;
}
else
statusBarMsg("Annotation saved successfully.");
}
void AnnotatorWnd::overlayRescaleTriggered()
{
QAction *action = qobject_cast<QAction *>(sender());
int idx = action->data().toInt();
// ask for gaussian variance
bool ok = false;
float scale = QInputDialog::getDouble(0, "Scale", "Specify value used to rescale overlay", 0.5, 0.1, 1.0f, 1, &ok);
if (!ok) return;
// generate list of seeds
Matrix3D<OverlayType>* dataOverlay = mOverlayVolumeList[idx];
for(int x = 0; x < dataOverlay->width(); ++x) {
for(int y = 0; y < dataOverlay->height(); ++y) {
for(int z = 0; z < dataOverlay->depth(); ++z) {
(*dataOverlay)(x,y,z) *= scale;
}
}
}
updateImageSlice();
}
Matrix3D<OverlayType> & AnnotatorWnd::getOverlayVoxelData( unsigned int num )
{
return *mOverlayVolumeList.at(num); // note the assert on num!
}
Matrix3D<OverlayType> * AnnotatorWnd::getSelectedOverlayData( )
{
int overlayindex = ui->layersDisplay->currentIndex().row();
if(overlayindex >= 0 && overlayindex < mOverlayVolumeList.size() )
{
Matrix3D<OverlayType> *annotationData = mOverlayVolumeList.at(overlayindex);
if (annotationData->isEmpty())
{
annotationData->reallocSizeLike( getVolumeVoxelData() );
annotationData->fill(0);
mOverlayMenuActions[overlayindex]->setChecked(true);
mOverlayMenuActions[overlayindex]->setEnabled(true);
}
return annotationData;
} else
{
throw std::runtime_error("Invalid overlay index. Is any selected?");
}
}
void AnnotatorWnd::setOverlayVisible( unsigned int num, bool visible )
{
// we will only set it visible if it contains valid info
if (!mOverlayVolumeList.at(num)->isSizeLike( mVolumeData )) {
qDebug() << "Overlay visible command ignored because overlay is not valid yet.";
mOverlayMenuActions.at(num)->setEnabled(false);
mOverlayMenuActions.at(num)->setChecked(false);
return;
}
mOverlayMenuActions.at(num)->setEnabled(visible);
mOverlayMenuActions.at(num)->setChecked(visible);
updateImageSlice();
}
void AnnotatorWnd::scanPlugins( const QString &pluginFolder )
{
// list files
QDir dir(pluginFolder);
dir.setFilter(QDir::Files);
dir.setSorting(QDir::Name);
qDebug() << "Plugin folder: " << pluginFolder;
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i)
{
QFileInfo fileInfo = list.at(i);
QString absFilePath = fileInfo.absoluteFilePath();
if ( !QLibrary::isLibrary( absFilePath ) )
continue;
QLibrary *library = new QLibrary( absFilePath, this );
if (!library->load()) {
qDebug() << "Could not load plugin " << absFilePath << ":" << library->errorString();
continue;
}
typedef PluginBase*(*PluginCreateFunction)(void);
PluginCreateFunction createPlugin = (PluginCreateFunction) library->resolve("createPlugin");
if (createPlugin == 0) {
qDebug() << "Could not resolve entry point for plugin " << absFilePath;
continue;
}
PluginBase *newPlugin = createPlugin();
mPluginBaseList.push_back( newPlugin );
mPluginServList.append( PluginServices( newPlugin->pluginName(), this ) );
bool ret = newPlugin->initializePlugin( mPluginServList.last() );
mPluginLibList.push_back( library );
if (!ret)
{
qDebug() << "Initialization failed for " << absFilePath;
continue;
}
}
if ( mPluginServList.isEmpty() )
ui->menuPlugins->addAction( "No plugins loaded" )->setEnabled(false);
}
void AnnotatorWnd::loadSettings()
{
QSettings settings(m_sSettingsFile, QSettings::NativeFormat);
mSettingsData.savePath = settings.value("savePath", ".").toString();
mSettingsData.loadPath = settings.value("loadPath", ".").toString();
mSettingsData.loadPathScores = settings.value("loadPathScores", ".").toString();
mSettingsData.loadPathVolume = settings.value("loadPathVolume", ".").toString();
mSettingsData.fijiExePath = settings.value("fijiExePath", "Not set").toString();
mSettingsData.maxVoxForSVox = settings.value("maxVoxForSVox", 28000000).toUInt();
ui->spinSVCubeness->setValue( settings.value("spinSVCubeness", 40).toInt() );
ui->spinSVSeed->setValue( settings.value("spinSVSeed", 20).toInt() );
ui->spinSVZ->setValue( settings.value("spinSVZ", 100).toInt() );
}
void AnnotatorWnd::saveSettings()
{
QSettings settings(m_sSettingsFile, QSettings::NativeFormat);
settings.setValue( "savePath", mSettingsData.savePath );
settings.setValue( "loadPath", mSettingsData.loadPath );
settings.setValue( "loadPathScores", mSettingsData.loadPathScores );
settings.setValue( "loadPathVolume", mSettingsData.loadPathVolume );
settings.setValue("spinSVCubeness", ui->spinSVCubeness->value());
settings.setValue("spinSVSeed", ui->spinSVSeed->value());
settings.setValue( "spinSVZ", ui->spinSVZ->value() );
settings.setValue( "fijiExePath", mSettingsData.fijiExePath );
settings.setValue( "maxVoxForSVox", mSettingsData.maxVoxForSVox );
settings.setValue( "sliceJump", mSettingsData.sliceJump );
qDebug() << m_sSettingsFile;
}
void AnnotatorWnd::actionLoadScoreImageTriggered()
{
QString fileName = QFileDialog::getOpenFileName( this, "Load score image", mSettingsData.loadPathScores, mFileTypeFilter );
if (fileName.isEmpty())
return;
qDebug() << fileName;
std::string stdFName = fileName.toLocal8Bit().constData();
if (!mScoreImage.load( stdFName ))
QMessageBox::critical(this, "Cannot open file", QString("%1 could not be read.").arg(fileName));
if ( !mScoreImage.isSizeLike( mVolumeData ) )
{
QMessageBox::critical(this, "Dimensions do not match", "Score image does not match original volume dimensions. Disabling score visualization.");
mScoreImageEnabled = false;
ui->actionScoreImageEnabled->setChecked(mScoreImageEnabled);
ui->chkConnectivityScoreImg->setEnabled(mScoreImageEnabled);
ui->chkScoreEnable->setEnabled(mScoreImageEnabled);
updateImageSlice();
return;
}
// enable and show ;)
mScoreImageEnabled = true;
ui->actionScoreImageEnabled->setChecked(mScoreImageEnabled);
ui->chkConnectivityScoreImg->setEnabled(mScoreImageEnabled);
ui->chkScoreEnable->setEnabled(mScoreImageEnabled);
updateImageSlice();
statusBarMsg("Score image loaded successfully.");
mSettingsData.loadPathScores = QFileInfo(fileName).absolutePath();
this->saveSettings();
}
void AnnotatorWnd::actionEnableScoreImageTriggered()
{
if ( !mScoreImage.isSizeLike( mVolumeData ) ) {
ui->actionScoreImageEnabled->setChecked(false);
return;
}
mScoreImageEnabled = ui->actionScoreImageEnabled->isChecked();
updateImageSlice();
}
bool AnnotatorWnd::saveAnnotation(const QString& fileName_)
{
QString fileName(fileName_);
if (!fileName.endsWith(".tif"))
fileName += ".tif";
qDebug() << fileName;
std::string stdFName = fileName.toLocal8Bit().constData();
if (!mVolumeLabels.save( stdFName )) {
statusBarMsg(QString("Error saving ") + fileName, 0 );
return false;
}
else
statusBarMsg("Annotation saved successfully.");
return true;
}
void AnnotatorWnd::actionSaveAnnotTriggered()
{
QString fileName;
if(mSettingsData.saveFilePath.isEmpty())
fileName = QFileDialog::getSaveFileName( this, "Save annotation", mSettingsData.savePath, mFileTypeFilter );
else
fileName = mSettingsData.saveFilePath;
if (fileName.isEmpty())
return;
if (!saveAnnotation(fileName))
return;
mSettingsData.savePath = QFileInfo(fileName).absolutePath();
mSettingsData.saveFilePath = QFileInfo(fileName).absoluteFilePath();
this->saveSettings();
}
bool AnnotatorWnd:: loadAnnotation(const QString& fileName, int importAsLabel, LabelType threshold)
{
qDebug() << fileName;
std::string stdFName = fileName.toLocal8Bit().constData();
if (!mVolumeLabels.load( stdFName )) {
QMessageBox::critical(this, "Cannot open file", QString("%1 could not be read.").arg(fileName));
return false;
}
if ( (mVolumeLabels.width() != mVolumeData.width()) || (mVolumeLabels.height() != mVolumeData.height()) || (mVolumeLabels.depth() != mVolumeData.depth()) )
{
QMessageBox::critical(this, "Dimensions do not match", "Annotation volume does not match original volume dimensions. Re-setting labels.");
mVolumeLabels.reallocSizeLike( mVolumeData );
mVolumeLabels.fill(0);
updateImageSlice();
return false;
}
// check if we have to import it
if ( importAsLabel >= 0 )
{
const unsigned numEl = mVolumeLabels.numElem();
const LabelType label = (unsigned char) importAsLabel;
for (unsigned i=0; i < numEl; i++)
{
if ( mVolumeLabels.data()[i] >= threshold )
mVolumeLabels.data()[i] = label;
else
mVolumeLabels.data()[i] = 0;
}
}
updateImageSlice();
statusBarMsg("Annotation loaded successfully.");
return true;
}
void AnnotatorWnd::actionImportAnnotTriggered()
{
QString fileName = QFileDialog::getOpenFileName( this, "Import annotation", mSettingsData.loadPath, mFileTypeFilter );
if (fileName.isEmpty())
return;
bool ok = false;
// ask for threshold
int threshold = QInputDialog::getInt( 0, "Threshold value", "Specify the thresholding value:",
128, 0, 255, 1, &ok );
if (!ok) return;
// prepare string list, without 'not-labeled' item
QStringList items;
for (unsigned i=1; i < ui->comboLabel->count(); i++)
items.append( ui->comboLabel->itemText(i) );
QString selectedItem = QInputDialog::getItem( 0, "Select label", "Label to assign to values higher than threshold:",
items, 0, false, &ok);
if (!ok) return;
int importAsLabel = items.indexOf( selectedItem ) + 1;
if (!loadAnnotation(fileName, importAsLabel, threshold))
return;
mSettingsData.loadPath = QFileInfo(fileName).absolutePath();
this->saveSettings();
}
void AnnotatorWnd::actionLoadAnnotTriggered()
{
QString fileName = QFileDialog::getOpenFileName( this, "Load annotation", mSettingsData.loadPath, mFileTypeFilter );
if (fileName.isEmpty())
return;
if (!loadAnnotation(fileName))
return;
mSettingsData.loadPath = QFileInfo(fileName).absolutePath();
this->saveSettings();
}
Region3D AnnotatorWnd::getViewportRegion3D()
{
// prepare Z range
int zMin = mCurZSlice - ui->spinSVZ->value();
int zMax = mCurZSlice + ui->spinSVZ->value();
if (zMin < 0) zMin = 0;
if (zMax >= mVolumeData.depth()) zMax = mVolumeData.depth() - 1;
// selected x,y region + whole z range
return Region3D( ui->labelImg->getViewableRect(), zMin, zMax - zMin + 1 );
}
// this is a helper for genSupervoxelClicked()
class SupervoxelThread : public QThread
{
public:
typedef SuperVoxeler<PixelType> SupervoxelerType;
typedef Matrix3D<PixelType> VolumeType;
protected:
SupervoxelerType &mSVox;
const VolumeType &mRawVolume;
int mSeed;
unsigned int mCubeness;
AnnotatorWnd *mParent;
public:
SupervoxelThread(AnnotatorWnd *parent, SupervoxelerType &svox, const VolumeType &raw,
int seed, unsigned int cubeness) : QThread(parent), mSVox(svox), mRawVolume(raw),
mSeed(seed), mCubeness(cubeness), mParent(parent)
{
}
public:
void run()
{
mSVox.apply( mRawVolume, mSeed, mCubeness );
QMetaObject::invokeMethod( mParent, "statusBarMsg", Qt::QueuedConnection, Q_ARG( QString, QString("Done: %1 supervoxels generated.").arg( mSVox.numLabels() ) ) );
}
};
void AnnotatorWnd::loadSuperVoxelWholeVolumeClicked()
{
QString fileName = QFileDialog::getOpenFileName( this, "Load supervoxel data", mSettingsData.loadPathScores, "nrrd (*.nrrd)" );
if (fileName.isEmpty())
return;
std::string stdFName = fileName.toLocal8Bit().constData();
if (!mSVoxel.load( stdFName )) {
QMessageBox::critical(this, "Cannot open file", QString("%1 could not be read.").arg(fileName));
return;
}
if ( (mSVoxel.pixelToVoxel().width() != mVolumeData.width()) || (mSVoxel.pixelToVoxel().height() != mVolumeData.height()) || (mSVoxel.pixelToVoxel().depth() != mVolumeData.depth()) )
{
QMessageBox::critical(this, "Dimensions do not match", "Supervoxel volume does not match original volume dimensions. Re-setting supervoxels.");
mSVRegion.valid = false;
updateImageSlice();
return;
}
mSVRegion.valid = true;
mSVRegion.corner.x = mSVRegion.corner.y = mSVRegion.corner.z = 0;
mSVRegion.size.x = mVolumeData.width();
mSVRegion.size.y = mVolumeData.height();
mSVRegion.size.z = mVolumeData.depth();
updateImageSlice();
statusBarMsg("Supervoxel data loaded successfully.");
}
void AnnotatorWnd::saveSuperVoxelWholeVolumeClicked()
{
bool isOk = true;
if (!mSVRegion.valid) isOk = false;
if ( (mSVRegion.corner.x != 0) || (mSVRegion.corner.y != 0) || (mSVRegion.corner.z != 0) ) isOk = false;
if ( mSVRegion.size.x != mVolumeData.width() ) isOk = false;