-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtvsegwindow.cpp
637 lines (533 loc) · 18.6 KB
/
tvsegwindow.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
#include "tvsegwindow.h"
#include "ui_tvsegwindow.h"
#include "util/valuetransition.h"
#include "algorithmwidget.h"
#include "tvseg/util/opencvhelper.h"
#include "tvseg/segmentationimpl.h"
#include "tvseg/feedbackbase.h"
#include "tvseg/settings/serializerqt.h"
#include "tvseg/util/logging.h"
#include "tvseg/util/helpers.h"
#include "tvseg/settingsdef/parzensettings.h"
#include "tvseg/settingsdef/weightsettings.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QFileDialog>
#include <QtConcurrent>
namespace tvseg_ui {
// TODO: Sychronize when calling segmentation methods in a worker thread. This includes access to logging, as well as the settings (backend, value objects).
namespace _detail {
void displayImageHelper(FeedbackWidget* w, const float* data, tvseg::Dim3 dim, std::string windowName) {
if (!w) {
LWARNING << "displayImageHelper received NULL widget";
return;
}
if (!data) {
LWARNING << "displayImageHelper received NULL data";
return;
}
w->displayCVImageAsync(tvseg::createMat(data, dim), windowName);
}
}
TVSegWindow::TVSegWindow(QWidget *parent, std::string settingsFilename) :
QMainWindow(parent),
ui_(new Ui::TVSegWindow),
settingsFilename_(settingsFilename),
settingsBackend_(new tvseg::settings::Backend()),
settingsSerializer_(new tvseg::settings::SerializerQt(settingsBackend_, settingsFilename_, true)),
uiSettings_(new UiSettings(settingsBackend_)),
inputSettings_(new tvseg::InputSettings(settingsBackend_)),
outputSettings_(new tvseg::OutputSettings(settingsBackend_)),
segmentationSettings_(new tvseg::SegmentationSettings(settingsBackend_)),
windowSettings_(new WindowSettings(settingsBackend_)),
segmentation_(new tvseg::SegmentationImpl(settingsBackend_)),
consoleDock_(new ConsoleDockWidget(this)),
feedbackDock_(new FeedbackDockWidget(this)),
mainSettingsEditor_(new SettingsEditor(this)),
solverWidget_(new AlgorithmWidget()),
stateMachine_(new QStateMachine(this)),
algorithmRunning_(false),
cancelRequested_(false)
{
ui_->setupUi(this);
addDockWidget(Qt::BottomDockWidgetArea, consoleDock_);
easyloggingpp::Loggers::getLogger("trivial")->registerDispatchCallback("gui_console",
boost::bind(&TVSegWindow::addConsoleMessageAsync, this, _1, _2));
addDockWidget(Qt::RightDockWidgetArea, feedbackDock_);
ui_->menuWindow->addAction(consoleDock_->toggleViewAction());
ui_->menuWindow->addAction(feedbackDock_->toggleViewAction());
QMenu *fileMenu = menuBar()->addMenu("&File");
QAction *quitAction = new QAction("&Quit", this); // on OS X this will be merged into the application menu
fileMenu->addAction(quitAction);
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
// image display
ui_->inputDisplay->setLabels(seg()->labels());
// feedback
tvseg::FeedbackBasePtr fb(new tvseg::FeedbackBase());
fb->setDisplayImageFn(boost::bind(&_detail::displayImageHelper, getFeedbackWidget(), _1, _2, _3));
fb->setProgressFn(boost::bind(&FeedbackWidget::updateProgressAsync, getFeedbackWidget(), _1, _2, _3));
fb->setCancelFlag(&cancelRequested_);
seg()->setFeedback(fb);
connect(getFeedbackWidget(), SIGNAL(cancelRequested()), this, SLOT(setCancelRequested()));
connect(this, SIGNAL(algorithmRunningChanged(bool)), getFeedbackWidget(), SLOT(setRunning(bool)));
// state machine
QState *sIdle = new QState();
QState *sRunning = new QState();
sRunning->assignProperty(ui_->centralWidget, "enabled", false);
sRunning->assignProperty(this, "cancelRequested", false);
sIdle->addTransition(util::ValueTransition<bool>::make(this, SIGNAL(algorithmRunningChanged(bool)), true, sRunning));
sRunning->addTransition(util::ValueTransition<bool>::make(this, SIGNAL(algorithmRunningChanged(bool)), false, sIdle));
stateMachine_->setGlobalRestorePolicy(QStateMachine::RestoreProperties);
stateMachine_->addState(sIdle);
stateMachine_->addState(sRunning);
stateMachine_->setInitialState(algorithmRunning() ? sRunning : sIdle);
stateMachine_->start();
// algorithm widgets
ui_->mainTabWidget->addTab(solverWidget_, "Solver");
solverWidget_->addAlgorithm(seg()->weightInterface());
solverWidget_->addAlgorithm(seg()->datatermInterface());
solverWidget_->addAlgorithm(seg()->solverInterface());
solverWidget_->addAlgorithm(seg()->visualizerInterface());
connect(solverWidget_, SIGNAL(algorithmStarted()), this, SLOT(algorithmStarted()));
connect(solverWidget_, SIGNAL(algorithmStopped()), this, SLOT(algorithmStopped()));
connect(solverWidget_, SIGNAL(runAll()), this, SLOT(runAllAlgorithms()));
connect(solverWidget_, SIGNAL(saveResult()), this, SLOT(saveResult()));
connect(solverWidget_, SIGNAL(computeMetrics()), this, SLOT(computeMetrics()));
connect(solverWidget_, SIGNAL(setPreset(QString)), this, SLOT(setPreset(QString)));
addPresets();
if (uiSettings()->autoRun()) {
ui_->mainTabWidget->setCurrentWidget(solverWidget_);
}
// settings editor
ui_->inputSidePane->addWidget(mainSettingsEditor_, 1);
connect(mainSettingsEditor_, SIGNAL(valueChanged(QtProperty*,QVariant)), this, SLOT(settingsValueChanged(QtProperty*,QVariant)));
mainSettingsEditor_->addEntries(*uiSettings_);
mainSettingsEditor_->addEntries(*segmentationSettings_);
mainSettingsEditor_->addEntries(*inputSettings_);
mainSettingsEditor_->addEntries(*outputSettings_);
// update GUI from settings
updateGUIFromSettings();
windowStateFromSettings();
}
TVSegWindow::~TVSegWindow()
{
easyloggingpp::Loggers::getLogger("trivial")->unregisterDispatchCallback("gui_console");
delete ui_;
}
//void TVSegWindow::setSettings(tvseg::settings::BackendPtr value, std::string filename)
//{
// settingsBackend_ = value;
// settingsSerializer_.reset(new tvseg::settings::SerializerQt(settingsBackend_, filename));
// //TODO: replace backend
// // settings_->replaceBackend();
// settings_.reset(new tvseg::InputSettings(value));
// seg()->setSettingsBackend(value);
// updateGUIFromSettings();
//}
tvseg::InputSettings::Ptr TVSegWindow::inputSettings()
{
return inputSettings_;
}
tvseg::InputSettings::ConstPtr TVSegWindow::inputSettings() const
{
return inputSettings_;
}
tvseg::OutputSettings::Ptr TVSegWindow::outputSettings()
{
return outputSettings_;
}
tvseg::OutputSettings::ConstPtr TVSegWindow::outputSettings() const
{
return outputSettings_;
}
UiSettings::Ptr TVSegWindow::uiSettings()
{
return uiSettings_;
}
UiSettings::ConstPtr TVSegWindow::uiSettings() const
{
return uiSettings_;
}
tvseg::SegmentationSettings::Ptr TVSegWindow::segmentationSettings()
{
return segmentationSettings_;
}
tvseg::SegmentationSettings::ConstPtr TVSegWindow::segmentationSettings() const
{
return segmentationSettings_;
}
TVSegWindow::WindowSettings::Ptr TVSegWindow::windowSettings()
{
return windowSettings_;
}
TVSegWindow::WindowSettings::ConstPtr TVSegWindow::windowSettings() const
{
return windowSettings_;
}
tvseg::SegmentationPtr TVSegWindow::seg()
{
return segmentation_;
}
tvseg::SegmentationConstPtr TVSegWindow::seg() const
{
return segmentation_;
}
void TVSegWindow::closeEvent(QCloseEvent *event)
{
// TODO: capture close applciation event
// TODO: check if algorithm is running, send cancel, allow force quit.
// TODO: menu with saveSettings
QMessageBox::StandardButton resBtn = QMessageBox::question( this, windowTitle(),
tr("Do you really want to close?"),
QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) {
event->ignore();
} else {
// if (algorithmRunning()) {
// }
windowStateToSettings();
on_saveSettingsButton_clicked();
QMainWindow::closeEvent(event);
}
}
void TVSegWindow::initFromSettings()
{
on_loadImageButton_clicked();
on_displayLabelsButton_clicked();
if (uiSettings()->autoRun()) {
runAllAlgorithms();
}
}
void TVSegWindow::addConsoleMessageAsync(uint level, const std::string &msg)
{
using easyloggingpp::Level;
QColor color;
switch (level) {
case Level::Info:
color = QColor(11, 36, 251); // blue
break;
case Level::Warning:
color = QColor(253, 164, 40); // orange
break;
case Level::Debug:
color = QColor(15, 127, 18); // green
break;
case Level::Error:
case Level::Fatal:
color = QColor(252, 13, 27); // red
break;
default:
color = Qt::black;
break;
}
QMetaObject::invokeMethod(consoleDock_, "addMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(msg)), Q_ARG(QColor, color));
}
bool TVSegWindow::algorithmRunning()
{
return algorithmRunning_;
}
bool TVSegWindow::cancelRequested()
{
return cancelRequested_;
}
void TVSegWindow::on_saveSettingsButton_clicked()
{
setAndSaveScribbles();
if (settingsSerializer_) {
settingsSerializer_->save();
} else {
LERROR << "No SettingsSerializer instantiated.";
}
}
void TVSegWindow::on_loadImageButton_clicked()
{
seg()->loadInput();
updateGUIFromSettings();
updateSettingsEditors();
if (seg()->inputImageColorAvailable()) {
ui_->inputDisplay->setImage(seg()->inputImageColor());
}
setScribblesToDisplayWidget(seg()->scribbles());
}
void TVSegWindow::updateGUIFromSettings()
{
ui_->inputDisplay->setBrushSize(uiSettings()->scribbleBrushSize());
ui_->inputDisplay->setBrushDensity(uiSettings()->scribbleBrushDensity());
}
void TVSegWindow::updateSettingsEditors()
{
mainSettingsEditor_->updateFromSettings();
solverWidget_->updateFromSettings();
}
void TVSegWindow::windowStateToSettings()
{
QByteArray bytes = saveGeometry();
WindowSettings::byte_array_t value(bytes.data(), bytes.data() + bytes.length());
windowSettings()->setGeometry(value);
bytes = saveState();
value.assign(bytes.data(), bytes.data() + bytes.length());
windowSettings()->setWindowState(value);
}
void TVSegWindow::windowStateFromSettings()
{
restoreGeometry(QByteArray::fromRawData(windowSettings()->geometry().data(), windowSettings()->geometry().size()));
restoreState(QByteArray::fromRawData(windowSettings()->windowState().data(), windowSettings()->windowState().size()));
}
void TVSegWindow::displayKMeans()
{
if (seg()->kMeansAvailable()) {
ui_->labelsDisplay->setImage(seg()->kMeans());
} else {
LWARNINGF("Cannot display %d means.", segmentationSettings()->numLabels());
}
}
void TVSegWindow::displayLabels()
{
if (seg()->labelsAvailable()) {
ui_->labelsDisplay->setImage(seg()->labels());
} else {
LWARNINGF("Cannot display %d labels.", segmentationSettings()->numLabels());
}
}
void TVSegWindow::setAlgorithmRunning(bool value)
{
if (algorithmRunning_ != value) {
algorithmRunning_ = value;
emit algorithmRunningChanged(value);
}
}
void TVSegWindow::setCancelRequested(bool value)
{
if (cancelRequested_ != value) {
cancelRequested_ = value;
emit cancelRequestedChanged(value);
}
}
void TVSegWindow::algorithmStarted()
{
setAlgorithmRunning(true);
}
void TVSegWindow::algorithmStopped()
{
setAlgorithmRunning(false);
// invoke next algorithm from event queue, not directly
QMetaObject::invokeMethod(this, "invokeNextAlgorithm", Qt::QueuedConnection);
}
void TVSegWindow::settingsValueChanged(QtProperty *property, QVariant /*value*/)
{
if (property->propertyName() == "numLabels") {
displayLabels();
ui_->inputDisplay->setLabels(seg()->labels());
}
if (property->propertyName() == "scribbleBrushSize" ||
property->propertyName() == "scribbleBrushDensity")
{
updateGUIFromSettings();
}
// LDEBUG << "tvsegwindow: Settings value changed " << property->propertyName() << ": '" << value.toString() << "'";
}
void TVSegWindow::runAllAlgorithms()
{
algorithm_queue_t functions;
functions.append(boost::bind(&AlgorithmWidget::computeButtonClicked, solverWidget_, 0));
functions.append(boost::bind(&AlgorithmWidget::computeButtonClicked, solverWidget_, 1));
functions.append(boost::bind(&AlgorithmWidget::computeButtonClicked, solverWidget_, 2));
functions.append(boost::bind(&AlgorithmWidget::computeButtonClicked, solverWidget_, 3));
invokeAlgorithmsSequentially(functions);
}
void TVSegWindow::saveResult()
{
seg()->saveResult();
}
void TVSegWindow::computeMetrics()
{
std::vector<float> metrics = seg()->computeMetrics();
if (metrics.size() > 0) {
std::stringstream ss;
for (uint i = 0; i < metrics.size(); ++i) {
ss << metrics[i] << " ";
}
LINFO << "Metrics: " << ss.str();
}
}
FeedbackWidget *TVSegWindow::getFeedbackWidget()
{
return feedbackDock_->getFeedbackWidget();
}
void TVSegWindow::invokeAlgorithmsSequentially(TVSegWindow::algorithm_queue_t queue)
{
algorithmQueue_ = queue;
invokeNextAlgorithm();
}
tvseg::Scribbles TVSegWindow::getScribblesFromDisplayWidget()
{
QVector<QVector<QPoint> > scribbles = ui_->inputDisplay->getScribbles();
tvseg::scribble_list_type list;
list.resize(scribbles.size());
for (int i = 0; i < scribbles.size(); ++i) {
for (int j = 0; j < scribbles[i].size(); ++j) {
list[i].push_back(cv::Point(scribbles[i][j].x(), scribbles[i][j].y()));
}
}
return tvseg::Scribbles(list);
}
void TVSegWindow::setScribblesToDisplayWidget(const tvseg::Scribbles &input)
{
const tvseg::scribble_list_type &scribbles = input.get();
QVector<QVector<QPoint> > tmp;
tmp.resize(scribbles.size());
for (uint i = 0; i < scribbles.size(); ++i) {
for (uint j = 0; j < scribbles[i].size(); ++j) {
tmp[i].push_back(QPoint(scribbles[i][j].x, scribbles[i][j].y));
}
}
ui_->inputDisplay->setScribbles(tmp);
}
void TVSegWindow::setAndSaveScribbles()
{
tvseg::Scribbles scribbles = getScribblesFromDisplayWidget();
seg()->setScribbles(scribbles);
// always save to local scribble file to make scribble editing persistent,
// and only save to instance specific file upon manual request by user
if (uiSettings()->saveScribbles()) {
seg()->saveScribbleImage("scribbles.png", scribbles);
}
}
void TVSegWindow::invokeNextAlgorithm()
{
if (!algorithmQueue_.empty()) {
boost::function<void()> algo = algorithmQueue_.front();
algorithmQueue_.pop_front();
algo();
}
}
namespace { // some helpers for the settings presets
void set2d(tvseg::ParzenSettings &s_p, tvseg::WeightSettings &s_w) {
s_w.set_useDepth(false);
s_w.set_useColor(true);
s_p.set_colorVariance(0.05);
s_p.set_depthVariance(0.20);
s_p.set_fixScribblePixels(true);
s_p.set_normalizeSpaceScale(true);
s_p.set_scribbleDistanceDepth(false);
s_p.set_scribbleDistanceFactor(1000);
s_p.set_scribbleDistancePerspective(false);
s_p.set_useColorKernel(true);
s_p.set_useDepthKernel(false);
s_p.set_useDistanceKernel(true);
s_p.set_useSpatiallyActiveScribbles(false);
}
void set3d(tvseg::ParzenSettings &s_p, tvseg::WeightSettings &s_w) {
set2d(s_p, s_w);
s_p.set_scribbleDistanceDepth(true);
s_p.set_scribbleDistancePerspective(false);
s_p.set_useDepthKernel(true);
s_p.set_useSpatiallyActiveScribbles(true);
}
void set3dNoColor(tvseg::ParzenSettings &s_p, tvseg::WeightSettings &s_w) {
set3d(s_p, s_w);
s_w.set_useDepth(true);
s_w.set_useColor(false);
s_p.set_useColorKernel(false);
}
void set3dDepthWeight(tvseg::ParzenSettings &s_p, tvseg::WeightSettings &s_w) {
set3d(s_p, s_w);
s_w.set_useDepth(true);
s_w.set_useColor(true);
}
void set3dNoDistance(tvseg::ParzenSettings &s_p, tvseg::WeightSettings &s_w) {
set3d(s_p, s_w);
s_p.set_useDistanceKernel(false);
}
}
void TVSegWindow::addPresets()
{
solverWidget_->addPreset("2d");
solverWidget_->addPreset("3d");
solverWidget_->addPreset("3d no color");
solverWidget_->addPreset("3d depth weight");
solverWidget_->addPreset("3d no distance");
}
void TVSegWindow::setPreset(QString name)
{
tvseg::ParzenSettings s_p(settingsBackend_);
tvseg::WeightSettings s_w(settingsBackend_);
if (name == "2d") {
set2d(s_p, s_w);
} else if (name == "3d") {
set3d(s_p, s_w);
} else if (name == "3d no color") {
set3dNoColor(s_p, s_w);
} else if (name == "3d depth weight") {
set3dDepthWeight(s_p, s_w);
} else if (name == "3d no distance") {
set3dNoDistance(s_p, s_w);
} else {
LERROR << "unknown settings preset '" << name << "'";
return;
}
LINFO << "updated settings with preset '" << name << "'";
solverWidget_->updateFromSettings();
}
void TVSegWindow::on_actionQuit_triggered()
{
qApp->quit();
}
void TVSegWindow::on_computeKMeansButton_clicked()
{
seg()->computeKMeans();
displayKMeans();
}
void TVSegWindow::on_displayLabelsButton_clicked()
{
displayLabels();
}
void TVSegWindow::on_pickImageButton_clicked()
{
QFileInfo currentFileName(QString::fromStdString(inputSettings()->color()));
QDir currentDir = currentFileName.dir();
if (!currentDir.exists()) {
currentDir = QDir::current();
}
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Color Image"), currentDir.path(), tr("Image Files (*.png *.jpg *.gif *.bmp)"));
fileName = QDir::current().relativeFilePath(fileName);
inputSettings()->set_color(fileName.toStdString());
mainSettingsEditor_->updateFromSettings();
on_loadImageButton_clicked();
}
void TVSegWindow::on_showColorButton_clicked()
{
if (seg()->inputImageColorAvailable()) {
ui_->inputDisplay->setImage(seg()->inputImageColor(), true);
}
}
void TVSegWindow::on_showDepthButton_clicked()
{
if (seg()->inputImageDepthAvailable()) {
ui_->inputDisplay->setImage(seg()->inputImageDepth(), true);
}
}
void TVSegWindow::on_showGroundTruthButton_clicked()
{
if (seg()->inputImageGroundTruthAvailable()) {
ui_->inputDisplay->setImage(seg()->inputImageGroundTruth(), true);
}
}
void TVSegWindow::on_mainTabWidget_currentChanged(int index)
{
if (ui_->mainTabWidget->widget(index) == solverWidget_) {
setAndSaveScribbles();
}
}
} // namespace tvseg_ui
void tvseg_ui::TVSegWindow::on_saveScribblesButton_clicked()
{
seg()->setScribbles(getScribblesFromDisplayWidget());
seg()->saveScribbles();
}
void tvseg_ui::TVSegWindow::on_saveLabelMappingButton_clicked()
{
seg()->saveInputGroundTruthLabelMapping();
}