-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1340 lines (1103 loc) · 47.3 KB
/
mainwindow.cpp
File metadata and controls
1340 lines (1103 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QFileDialog>
#include <QColorDialog>
#include <QKeyEvent>
#include <QShortcut>
#include <QCollator>
#include <QFile>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QSettings>
#include <QVBoxLayout>
#ifdef ONNXRUNTIME_AVAILABLE
#include <QProgressDialog>
#endif
#include <iomanip>
#include <cmath>
using std::ofstream;
using std::ifstream;
using std::string;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_S), this), &QShortcut::activated, this, &MainWindow::save_label_data);
connect(new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Delete), this), &QShortcut::activated, this, &MainWindow::clear_label_data);
connect(new QShortcut(QKeySequence(Qt::Key_S), this), &QShortcut::activated, this, &MainWindow::next_label);
connect(new QShortcut(QKeySequence(Qt::Key_W), this), &QShortcut::activated, this, &MainWindow::prev_label);
connect(new QShortcut(QKeySequence(Qt::Key_A), this), &QShortcut::activated, this, [this]() { prev_img(); });
connect(new QShortcut(QKeySequence(Qt::Key_D), this), &QShortcut::activated, this, [this]() { next_img(); });
connect(new QShortcut(QKeySequence(Qt::Key_Space), this), &QShortcut::activated, this, [this]() { next_img(); });
connect(new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_D), this), &QShortcut::activated, this, &MainWindow::remove_img);
connect(new QShortcut(QKeySequence(Qt::Key_Delete), this), &QShortcut::activated, this, &MainWindow::remove_img);
connect(new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_C), this), &QShortcut::activated, this, &MainWindow::copy_annotations);
connect(new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_V), this), &QShortcut::activated, this, &MainWindow::paste_annotations);
connect(new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_0), this), &QShortcut::activated, this, &MainWindow::reset_zoom);
ui->checkBox_visualize_class_name->setStyleSheet(
"QCheckBox { color: rgb(0, 255, 255); }"
"QCheckBox::indicator { width: 18px; height: 18px; border: 2px solid rgb(0, 255, 255); background-color: white; border-radius: 3px; }"
"QCheckBox::indicator:checked { background-color: rgb(0, 255, 255); }"
);
m_usageTimerElapsedSeconds = 0;
m_usageTimer = new QTimer(this);
m_usageTimer->setInterval(1000);
connect(m_usageTimer, &QTimer::timeout, this, &MainWindow::on_usageTimer_timeout);
m_usageTimer->start();
m_usageTimerLabel = new QLabel(this);
m_usageTimerLabel->setStyleSheet(
"color: rgb(0, 255, 255); font-weight: bold; font-family: 'Consolas', 'Courier New', monospace; font-size: 15px; padding: 2px 8px;"
);
m_usageTimerLabel->setMinimumWidth(150);
m_usageTimerResetButton = new QPushButton(QStringLiteral("\u21BA"), this);
m_usageTimerResetButton->setFixedSize(30, 30);
m_usageTimerResetButton->setToolTip(tr("Reset Timer"));
m_usageTimerResetButton->setStyleSheet(
"QPushButton { background-color: rgb(0, 0, 17); color: rgb(0, 255, 255); border: 1px solid rgb(0, 255, 255); border-radius: 15px; font-size: 18px; font-weight: bold; }"
"QPushButton:hover { background-color: rgb(0, 40, 60); }"
"QPushButton:pressed { background-color: rgb(0, 80, 100); }"
);
connect(m_usageTimerResetButton, &QPushButton::clicked, this, &MainWindow::on_usageTimerReset_clicked);
updateUsageTimerLabel();
ui->statusBar->setStyleSheet(
"QStatusBar { background-color: rgb(0, 0, 17); border: none; }"
"QStatusBar::item { border: none; }"
);
ui->statusBar->addPermanentWidget(m_usageTimerLabel);
ui->statusBar->addPermanentWidget(m_usageTimerResetButton);
QShortcut *undoShortcut = new QShortcut(QKeySequence::Undo, this);
undoShortcut->setContext(Qt::ApplicationShortcut);
connect(undoShortcut, &QShortcut::activated, this, &MainWindow::undo);
QShortcut *redoShortcut = new QShortcut(QKeySequence::Redo, this);
redoShortcut->setContext(Qt::ApplicationShortcut);
connect(redoShortcut, &QShortcut::activated, this, &MainWindow::redo);
#ifdef ONNXRUNTIME_AVAILABLE
// --- Auto-Label Controls ---
QString btnStyle =
"QPushButton { background-color: rgb(0, 0, 17); color: rgb(0, 255, 255); border: 2px solid rgb(0, 255, 255); border-radius: 4px; padding: 4px 8px; font-weight: bold; font-size: 12px; }"
"QPushButton:hover { background-color: rgb(0, 40, 60); }"
"QPushButton:pressed { background-color: rgb(0, 80, 100); }"
"QPushButton:disabled { color: rgb(80, 80, 80); border-color: rgb(80, 80, 80); }";
QString sliderStyle =
"QSlider::groove:horizontal { border: 1px solid rgb(0, 255, 255); height: 6px; background: rgb(0, 0, 17); border-radius: 3px; }"
"QSlider::handle:horizontal { background: rgb(255, 187, 0); border: 1px solid rgb(255, 187, 0); width: 14px; margin: -5px 0; border-radius: 7px; }";
QString labelStyle = "color: rgb(0, 255, 255); font-weight: bold; font-size: 12px;";
m_btnLoadModel = new QPushButton("Load Model", this);
m_btnLoadModel->setStyleSheet(btnStyle);
m_sliderConfidence = new QSlider(Qt::Horizontal, this);
m_sliderConfidence->setRange(1, 99);
m_sliderConfidence->setValue(25);
m_sliderConfidence->setFixedWidth(120);
m_sliderConfidence->setStyleSheet(sliderStyle);
m_labelConfidence = new QLabel("Conf: 25%", this);
m_labelConfidence->setStyleSheet(labelStyle);
m_labelConfidence->setFixedWidth(70);
m_btnAutoLabel = new QPushButton("Auto Label", this);
m_btnAutoLabel->setStyleSheet(btnStyle);
m_btnAutoLabel->setEnabled(false);
m_btnAutoLabel->setToolTip(tr("Auto-label current image (R)"));
m_btnAutoLabelAll = new QPushButton("Auto Label All", this);
m_btnAutoLabelAll->setStyleSheet(btnStyle);
m_btnAutoLabelAll->setEnabled(false);
m_labelModelStatus = new QLabel("No model loaded", this);
m_labelModelStatus->setStyleSheet(labelStyle);
QHBoxLayout *autoLabelLayout = new QHBoxLayout();
autoLabelLayout->setContentsMargins(0, 2, 0, 2);
autoLabelLayout->addWidget(m_btnLoadModel);
autoLabelLayout->addWidget(m_sliderConfidence);
autoLabelLayout->addWidget(m_labelConfidence);
autoLabelLayout->addWidget(m_btnAutoLabel);
autoLabelLayout->addWidget(m_btnAutoLabelAll);
autoLabelLayout->addWidget(m_labelModelStatus, 1);
ui->gridLayout->addLayout(autoLabelLayout, 1, 0);
connect(m_btnLoadModel, &QPushButton::clicked, this, &MainWindow::on_loadModel_clicked);
connect(m_btnAutoLabel, &QPushButton::clicked, this, &MainWindow::on_autoLabel_clicked);
connect(m_btnAutoLabelAll, &QPushButton::clicked, this, &MainWindow::on_autoLabelAll_clicked);
connect(m_sliderConfidence, &QSlider::valueChanged, this, &MainWindow::on_confidenceSlider_changed);
connect(new QShortcut(QKeySequence(Qt::Key_R), this), &QShortcut::activated, this, &MainWindow::on_autoLabel_clicked);
#endif
// ── Cloud auto-label setup ─────────────────────────────────────────
{
QSettings s("YoloLabel", "CloudAI");
m_cloudApiKey = s.value("apiKey", "").toString();
m_cloudPrompt = s.value("prompt", "").toString();
}
m_cloudLabeler = new CloudAutoLabeler(this);
m_cloudLabeler->setApiKey(m_cloudApiKey);
m_cloudLabeler->setPrompt(m_cloudPrompt);
connect(m_cloudLabeler, &CloudAutoLabeler::busyChanged, this, [this](bool busy) {
// Disable image slider while a batch is running to prevent navigation
ui->horizontalSlider_images->setEnabled(!busy);
if (!busy) resetCloudButtons();
});
connect(m_cloudLabeler, &CloudAutoLabeler::progress, this, [this](int done, int total) {
m_btnCloudAutoLabelAll->setText(
QString("\u2601 Auto Label All (%1/%2)\u2026").arg(done).arg(total));
});
connect(m_cloudLabeler, &CloudAutoLabeler::labelReady, this,
[this](const QString &imagePath, int /*n*/, int /*ms*/) {
if (imagePath == m_imgList.value(m_imgIndex))
goto_img(m_imgIndex);
});
connect(m_cloudLabeler, &CloudAutoLabeler::finished, this, [this](int) {
goto_img(m_imgIndex);
});
connect(m_cloudLabeler, &CloudAutoLabeler::errorOccurred, this, [this](const QString &msg) {
QMessageBox::warning(this, "Auto Label", msg);
});
connect(m_cloudLabeler, &CloudAutoLabeler::statusMessage, this,
[this](const QString &msg, int ms) {
statusBar()->showMessage(msg, ms);
});
QString cloudBtnStyle =
"QPushButton { background-color: rgb(0, 0, 17); color: rgb(0, 255, 255); "
"border: 2px solid rgb(0, 255, 255); border-radius: 4px; padding: 4px 12px; "
"font-weight: bold; font-size: 12px; }"
"QPushButton:hover { background-color: rgb(0, 40, 60); }"
"QPushButton:pressed { background-color: rgb(0, 80, 100); }"
"QPushButton:disabled { color: rgb(80,80,80); border-color: rgb(80,80,80); }";
m_btnCloudAutoLabel = new QPushButton("\u2601 Auto Label AI", this);
m_btnCloudAutoLabel->setToolTip("Label current image using cloud AI");
m_btnCloudAutoLabel->setStyleSheet(cloudBtnStyle);
connect(m_btnCloudAutoLabel, &QPushButton::clicked, this, &MainWindow::submitCloudJob);
m_btnCloudAutoLabelAll = new QPushButton("\u2601 Auto Label All AI", this);
m_btnCloudAutoLabelAll->setToolTip("Label all images using cloud AI");
m_btnCloudAutoLabelAll->setStyleSheet(cloudBtnStyle);
connect(m_btnCloudAutoLabelAll, &QPushButton::clicked, this, &MainWindow::cloudAutoLabelAll);
m_btnCancelAutoLabel = new QPushButton("\u2715 Cancel", this);
m_btnCancelAutoLabel->setToolTip("Cancel cloud auto-labeling");
m_btnCancelAutoLabel->setStyleSheet(
"QPushButton { background-color: rgb(0, 0, 17); color: rgb(255, 80, 80); "
"border: 2px solid rgb(255, 80, 80); border-radius: 4px; padding: 4px 12px; "
"font-weight: bold; font-size: 12px; }"
"QPushButton:hover { background-color: rgb(40, 0, 0); }");
m_btnCancelAutoLabel->setVisible(false);
connect(m_btnCancelAutoLabel, &QPushButton::clicked, this, &MainWindow::cancelAutoLabel);
{
QHBoxLayout *cloudLayout = new QHBoxLayout();
cloudLayout->setContentsMargins(0, 2, 0, 2);
cloudLayout->addWidget(m_btnCloudAutoLabel);
cloudLayout->addWidget(m_btnCloudAutoLabelAll);
cloudLayout->addWidget(m_btnCancelAutoLabel);
cloudLayout->addStretch();
// Insert below the ONNX auto-label row (or at row 1 if ONNX is not built)
int cloudRow = ui->gridLayout->rowCount();
ui->gridLayout->addLayout(cloudLayout, cloudRow, 0);
}
initSideTabWidget();
// ──────────────────────────────────────────────────────────────────
init_table_widget();
QTimer::singleShot(0, this, &MainWindow::restoreLastSession);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::set_args(int argc, char *argv[])
{
if (argc > 1) {
QString dir = QString::fromLocal8Bit(argv[1]);
if (!get_files(dir)) return;
QString onnxModelPath;
for (int i = 2; i < argc; ++i) {
QString arg = QString::fromLocal8Bit(argv[i]);
if (arg.endsWith(".onnx", Qt::CaseInsensitive)) {
onnxModelPath = arg;
} else {
m_objFilePath = arg;
load_label_list_data(arg);
}
}
#ifdef ONNXRUNTIME_AVAILABLE
if (!onnxModelPath.isEmpty()) {
loadOnnxModel(onnxModelPath);
}
#else
Q_UNUSED(onnxModelPath);
#endif
if (m_objList.empty()) return;
init();
}
}
void MainWindow::on_pushButton_open_files_clicked()
{
bool bRetImgDir = false;
open_img_dir(bRetImgDir);
if (!bRetImgDir) return ;
if (m_objList.empty())
{
bool bRetObjFile = false;
open_obj_file(bRetObjFile);
if (!bRetObjFile) return ;
}
init();
}
void MainWindow::init()
{
m_lastLabeledImgIndex = -1;
ui->label_image->init();
init_horizontal_slider();
#ifdef ONNXRUNTIME_AVAILABLE
if (m_detector.isLoaded()) {
m_btnAutoLabel->setEnabled(true);
m_btnAutoLabelAll->setEnabled(true);
}
#endif
set_label(0);
goto_img(0);
saveSession();
}
void MainWindow::saveSession()
{
QSettings s("YoloLabel", "Session");
s.setValue("imgDir", m_imgDir);
s.setValue("objFile", m_objFilePath);
QStringList colors;
for (const QColor &c : ui->label_image->m_drawObjectBoxColor)
colors << c.name();
s.setValue("classColors", colors);
}
void MainWindow::restoreLastSession()
{
// Skip if set_args() already loaded a folder
if (!m_imgList.isEmpty()) return;
QSettings s("YoloLabel", "Session");
const QString lastDir = s.value("imgDir").toString();
const QString lastObj = s.value("objFile").toString();
if (lastDir.isEmpty() || !QDir(lastDir).exists()) return;
if (!get_files(lastDir)) return;
QStringList savedColors;
if (!lastObj.isEmpty() && QFile::exists(lastObj)) {
m_objFilePath = lastObj;
load_label_list_data(lastObj);
savedColors = s.value("classColors").toStringList();
} else if (m_objList.isEmpty()) {
bool bRet = false;
open_obj_file(bRet);
if (!bRet) return;
}
init();
// Restore custom class colors after init() so they aren't overwritten
for (int i = 0; i < savedColors.size() && i < ui->label_image->m_drawObjectBoxColor.size(); ++i) {
QColor c(savedColors[i]);
if (!c.isValid()) continue;
ui->label_image->m_drawObjectBoxColor[i] = c;
if (ui->tableWidget_label->item(i, 1))
ui->tableWidget_label->item(i, 1)->setBackground(c);
}
ui->label_image->showImage();
statusBar()->showMessage("Session restored: " + lastDir, 4000);
}
void MainWindow::set_label_progress(const int fileIndex)
{
QString strCurFileIndex = QString::number(fileIndex + 1);
QString strEndFileIndex = QString::number(m_imgList.size());
ui->label_progress->setText(strCurFileIndex + " / " + strEndFileIndex);
}
void MainWindow::set_focused_file(const int fileIndex)
{
QString str = "";
if(m_lastLabeledImgIndex >= 0)
{
str += "Last Labeled Image: " + m_imgList.at(m_lastLabeledImgIndex);
str += '\n';
}
str += "Current Image: " + m_imgList.at(fileIndex);
ui->textEdit_log->setText(str);
}
void MainWindow::goto_img(const int fileIndex)
{
if (m_imgList.isEmpty() || fileIndex < 0 || fileIndex >= m_imgList.size()) return;
m_imgIndex = fileIndex;
bool bImgOpened;
ui->label_image->openImage(m_imgList.at(m_imgIndex), bImgOpened);
ui->label_image->resetZoom();
ui->label_image->clearUndoHistory();
ui->label_image->loadLabelData(get_labeling_data(m_imgList.at(m_imgIndex)));
ui->label_image->showImage();
set_label_progress(m_imgIndex);
set_focused_file(m_imgIndex);
//it blocks crash with slider change
ui->horizontalSlider_images->blockSignals(true);
ui->horizontalSlider_images->setValue(m_imgIndex);
ui->horizontalSlider_images->blockSignals(false);
}
void MainWindow::next_img(bool bSavePrev)
{
if (m_cloudLabeler && m_cloudLabeler->isBusy()) return;
if(bSavePrev && ui->label_image->isOpened()) save_label_data();
goto_img(m_imgIndex + 1);
}
void MainWindow::prev_img(bool bSavePrev)
{
if (m_cloudLabeler && m_cloudLabeler->isBusy()) return;
if(bSavePrev && ui->label_image->isOpened()) save_label_data();
goto_img(m_imgIndex - 1);
}
void MainWindow::save_label_data()
{
if(m_imgList.size() == 0) return;
QString qstrOutputLabelData = get_labeling_data(m_imgList.at(m_imgIndex));
ofstream fileOutputLabelData(qPrintable(qstrOutputLabelData));
if(fileOutputLabelData.is_open())
{
for(int i = 0; i < ui->label_image->m_objBoundingBoxes.size(); i++)
{
ObjectLabelingBox objBox = ui->label_image->m_objBoundingBoxes[i];
double midX = objBox.box.x() + objBox.box.width() / 2.;
double midY = objBox.box.y() + objBox.box.height() / 2.;
double width = objBox.box.width();
double height = objBox.box.height();
fileOutputLabelData << objBox.label;
fileOutputLabelData << " ";
fileOutputLabelData << std::fixed << std::setprecision(6) << midX;
fileOutputLabelData << " ";
fileOutputLabelData << std::fixed << std::setprecision(6) << midY;
fileOutputLabelData << " ";
fileOutputLabelData << std::fixed << std::setprecision(6) << width;
fileOutputLabelData << " ";
fileOutputLabelData << std::fixed << std::setprecision(6) << height << std::endl;
}
m_lastLabeledImgIndex = m_imgIndex;
fileOutputLabelData.close();
}
}
void MainWindow::clear_label_data()
{
ui->label_image->clearAllBoxes();
ui->label_image->showImage();
}
void MainWindow::remove_img()
{
if(m_imgList.size() > 0) {
//remove a image
QFile::remove(m_imgList.at(m_imgIndex));
//remove a txt file
QString qstrOutputLabelData = get_labeling_data(m_imgList.at(m_imgIndex));
QFile::remove(qstrOutputLabelData);
m_imgList.removeAt(m_imgIndex);
if(m_imgList.size() == 0)
{
pjreddie_style_msgBox(QMessageBox::Information,"End", "In directory, there are not any image. program quit.");
QCoreApplication::quit();
}
else if( m_imgIndex == m_imgList.size())
{
m_imgIndex--;
}
ui->horizontalSlider_images->setRange(0, m_imgList.size() - 1);
goto_img(m_imgIndex);
}
}
void MainWindow::next_label()
{
set_label(m_objIndex + 1);
}
void MainWindow::prev_label()
{
set_label(m_objIndex - 1);
}
void MainWindow::load_label_list_data(QString qstrLabelListFile)
{
ifstream inputLabelListFile(qPrintable(qstrLabelListFile));
if(inputLabelListFile.is_open())
{
for(int i = 0 ; i <= ui->tableWidget_label->rowCount(); i++)
ui->tableWidget_label->removeRow(ui->tableWidget_label->currentRow());
m_objList.clear();
ui->tableWidget_label->setRowCount(0);
ui->label_image->m_drawObjectBoxColor.clear();
string strLabel;
int fileIndex = 0;
while(getline(inputLabelListFile, strLabel))
{
int nRow = ui->tableWidget_label->rowCount();
QString qstrLabel = QString().fromStdString(strLabel);
QColor labelColor = label_img::BOX_COLORS[(fileIndex++)%10];
m_objList << qstrLabel;
ui->tableWidget_label->insertRow(nRow);
ui->tableWidget_label->setItem(nRow, 0, new QTableWidgetItem(qstrLabel));
ui->tableWidget_label->item(nRow, 0)->setFlags(ui->tableWidget_label->item(nRow, 0)->flags() ^ Qt::ItemIsEditable);
ui->tableWidget_label->setItem(nRow, 1, new QTableWidgetItem(QString().fromStdString("")));
ui->tableWidget_label->item(nRow, 1)->setBackground(labelColor);
ui->tableWidget_label->item(nRow, 1)->setFlags(ui->tableWidget_label->item(nRow, 1)->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
ui->label_image->m_drawObjectBoxColor.push_back(labelColor);
}
ui->label_image->m_objList = m_objList;
}
}
QString MainWindow::get_labeling_data(QString qstrImgFile)const
{
string strImgFile = qstrImgFile.toStdString();
string strLabelData = strImgFile.substr(0, strImgFile.find_last_of('.')) + ".txt";
return QString().fromStdString(strLabelData);
}
void MainWindow::set_label(const int labelIndex)
{
bool bIndexIsOutOfRange = (labelIndex < 0 || labelIndex > m_objList.size() - 1);
if(!bIndexIsOutOfRange)
{
m_objIndex = labelIndex;
ui->label_image->setFocusObjectLabel(m_objIndex);
ui->tableWidget_label->setCurrentCell(m_objIndex, 0);
}
}
void MainWindow::set_label_color(const int index, const QColor color)
{
ui->label_image->m_drawObjectBoxColor.replace(index, color);
}
void MainWindow::pjreddie_style_msgBox(QMessageBox::Icon icon, QString title, QString content)
{
QMessageBox msgBox(icon, title, content, QMessageBox::Ok);
QFont font;
font.setBold(true);
msgBox.setFont(font);
msgBox.button(QMessageBox::Ok)->setFont(font);
msgBox.button(QMessageBox::Ok)->setStyleSheet("border-style: outset; border-width: 2px; border-color: rgb(0, 255, 0); color : rgb(0, 255, 0);");
msgBox.button(QMessageBox::Ok)->setFocusPolicy(Qt::ClickFocus);
msgBox.setStyleSheet("background-color : rgb(34, 0, 85); color : rgb(0, 255, 0);");
msgBox.exec();
}
bool MainWindow::get_files(QString imgDir)
{
bool value = false;
QDir dir(imgDir);
QCollator collator;
collator.setNumericMode(true);
QStringList fileList = dir.entryList(
QStringList() << "*.jpg" << "*.JPG" << "*.png" << "*.bmp",
QDir::Files);
std::sort(fileList.begin(), fileList.end(), collator);
if(!fileList.empty())
{
value = true;
m_imgDir = imgDir;
m_imgList = fileList;
for(QString& str: m_imgList)
str = m_imgDir + "/" + str;
}
return value;
}
void MainWindow::open_img_dir(bool& ret)
{
pjreddie_style_msgBox(QMessageBox::Information,"Help", "Step 1. Open Your Data Set Directory");
QString opened_dir;
if(m_imgDir.size() > 0) opened_dir = m_imgDir;
else opened_dir = QCoreApplication::applicationDirPath();
QString imgDir = QFileDialog::getExistingDirectory(
nullptr,
tr("Open Dataset Directory"),
opened_dir,
QFileDialog::ShowDirsOnly);
if(imgDir.isEmpty())
{
ret = false;
return;
}
ret = get_files(imgDir);
if (!ret)
pjreddie_style_msgBox(QMessageBox::Critical,"Error", "This folder is empty");
}
void MainWindow::open_obj_file(bool& ret)
{
pjreddie_style_msgBox(QMessageBox::Information,"Help", "Step 2. Open Your Label List File(*.txt or *.names)");
QString opened_dir;
if(m_imgDir.size() > 0) opened_dir = m_imgDir;
else opened_dir = QCoreApplication::applicationDirPath();
QString fileLabelList = QFileDialog::getOpenFileName(
nullptr,
tr("Open LabelList file"),
opened_dir,
tr("LabelList Files (*.txt *.names)"));
if(fileLabelList.size() == 0)
{
ret = false;
pjreddie_style_msgBox(QMessageBox::Critical,"Error", "LabelList file is not opened()");
}
else
{
ret = true;
m_objFilePath = fileLabelList;
load_label_list_data(fileLabelList);
}
}
void MainWindow::wheelEvent(QWheelEvent *ev)
{
QPoint labelPos = ui->label_image->mapFromGlobal(ev->globalPosition().toPoint());
bool overImage = ui->label_image->rect().contains(labelPos);
if(ev->modifiers() & Qt::ControlModifier && overImage)
{
if(ev->angleDelta().y() > 0)
ui->label_image->zoomIn(labelPos);
else if(ev->angleDelta().y() < 0)
ui->label_image->zoomOut(labelPos);
}
else if(overImage)
{
if(ev->angleDelta().y() > 0)
prev_img();
else if(ev->angleDelta().y() < 0)
next_img();
}
}
void MainWindow::on_pushButton_prev_clicked()
{
prev_img();
}
void MainWindow::on_pushButton_next_clicked()
{
next_img();
}
void MainWindow::keyPressEvent(QKeyEvent * event)
{
int nKey = event->key();
bool graveAccentKeyIsPressed = (nKey == Qt::Key_QuoteLeft);
bool numKeyIsPressed = (nKey >= Qt::Key_0 && nKey <= Qt::Key_9 );
bool arrowKeyIsPressed = (nKey == Qt::Key_Up || nKey == Qt::Key_Down ||
nKey == Qt::Key_Left || nKey == Qt::Key_Right);
if(graveAccentKeyIsPressed)
{
set_label(0);
}
else if(numKeyIsPressed)
{
int asciiToNumber = nKey - Qt::Key_0;
if(asciiToNumber < m_objList.size() )
{
set_label(asciiToNumber);
}
}
else if(arrowKeyIsPressed && ui->label_image->isOpened())
{
static int nudgeBoxIdx = -1;
if(!event->isAutoRepeat())
{
QPointF cursorPos = ui->label_image->cvtAbsoluteToRelativePoint(
ui->label_image->mapFromGlobal(QCursor::pos()));
nudgeBoxIdx = ui->label_image->findBoxUnderCursor(cursorPos);
if(nudgeBoxIdx != -1)
ui->label_image->saveState();
}
if(nudgeBoxIdx != -1)
{
bool ctrlHeld = (event->modifiers() & Qt::ControlModifier);
bool shiftHeld = (event->modifiers() & Qt::ShiftModifier);
double step = shiftHeld ? 0.01 : 0.002;
if(ctrlHeld)
{
double dw = 0.0, dh = 0.0;
if(nKey == Qt::Key_Left) dw = -step;
if(nKey == Qt::Key_Right) dw = step;
if(nKey == Qt::Key_Up) dh = -step;
if(nKey == Qt::Key_Down) dh = step;
ui->label_image->resizeBox(nudgeBoxIdx, dw, dh);
}
else
{
double dx = 0.0, dy = 0.0;
if(nKey == Qt::Key_Left) dx = -step;
if(nKey == Qt::Key_Right) dx = step;
if(nKey == Qt::Key_Up) dy = -step;
if(nKey == Qt::Key_Down) dy = step;
ui->label_image->moveBox(nudgeBoxIdx, dx, dy);
}
}
}
}
void MainWindow::on_tableWidget_label_cellDoubleClicked(int row, int column)
{
bool bColorAttributeClicked = (column == 1);
if(bColorAttributeClicked)
{
QColor color = QColorDialog::getColor(Qt::white,nullptr,"Set Label Color");
if(color.isValid())
{
set_label_color(row, color);
ui->tableWidget_label->item(row, 1)->setBackground(color);
saveSession();
}
set_label(row);
ui->label_image->showImage();
}
}
void MainWindow::on_tableWidget_label_cellClicked(int row, int column)
{
set_label(row);
}
void MainWindow::on_horizontalSlider_images_sliderMoved(int position)
{
goto_img(position);
}
void MainWindow::init_horizontal_slider()
{
ui->horizontalSlider_images->setEnabled(true);
ui->horizontalSlider_images->setRange(0, m_imgList.size() - 1);
ui->horizontalSlider_images->blockSignals(true);
ui->horizontalSlider_images->setValue(0);
ui->horizontalSlider_images->blockSignals(false);
ui->horizontalSlider_contrast->setEnabled(true);
ui->horizontalSlider_contrast->setRange(0, 1000);
ui->horizontalSlider_contrast->setValue(ui->horizontalSlider_contrast->maximum()/2);
ui->label_image->setContrastGamma(1.0);
ui->label_contrast->setText(QString("Contrast(%) ") + QString::number(50));
}
void MainWindow::init_table_widget()
{
ui->tableWidget_label->horizontalHeader()->setVisible(true);
ui->tableWidget_label->horizontalHeader()->setStyleSheet("");
ui->tableWidget_label->horizontalHeader()->setStretchLastSection(true);
disconnect(ui->tableWidget_label->horizontalHeader(), &QHeaderView::sectionPressed, ui->tableWidget_label, &QTableWidget::selectColumn);
}
void MainWindow::on_horizontalSlider_contrast_sliderMoved(int value)
{
float valueToPercentage = float(value)/ui->horizontalSlider_contrast->maximum(); //[0, 1.0]
float percentageToGamma = std::pow(1/(valueToPercentage + 0.5), 7.);
ui->label_image->setContrastGamma(percentageToGamma);
ui->label_contrast->setText(QString("Contrast(%) ") + QString::number(int(valueToPercentage * 100.)));
}
void MainWindow::on_checkBox_visualize_class_name_clicked(bool checked)
{
ui->label_image->m_bVisualizeClassName = checked;
ui->label_image->showImage();
}
void MainWindow::copy_annotations()
{
if(!ui->label_image->isOpened()) return;
m_copiedAnnotations = ui->label_image->m_objBoundingBoxes;
}
void MainWindow::paste_annotations()
{
if(m_copiedAnnotations.isEmpty() || !ui->label_image->isOpened()) return;
ui->label_image->saveState();
ui->label_image->m_objBoundingBoxes = m_copiedAnnotations;
ui->label_image->showImage();
}
void MainWindow::undo()
{
if(ui->label_image->undo())
ui->label_image->showImage();
}
void MainWindow::redo()
{
if(ui->label_image->redo())
ui->label_image->showImage();
}
void MainWindow::on_usageTimer_timeout()
{
if (isActiveWindow())
{
m_usageTimerElapsedSeconds++;
updateUsageTimerLabel();
}
}
void MainWindow::on_usageTimerReset_clicked()
{
m_usageTimerElapsedSeconds = 0;
updateUsageTimerLabel();
}
void MainWindow::updateUsageTimerLabel()
{
qint64 secs = m_usageTimerElapsedSeconds;
int hours = static_cast<int>(secs / 3600);
int mins = static_cast<int>((secs % 3600) / 60);
int s = static_cast<int>(secs % 60);
QString text = QStringLiteral("\u23F1 %1:%2:%3")
.arg(hours, 2, 10, QChar('0'))
.arg(mins, 2, 10, QChar('0'))
.arg(s, 2, 10, QChar('0'));
m_usageTimerLabel->setText(text);
}
void MainWindow::reset_zoom()
{
ui->label_image->resetZoom();
}
#ifdef ONNXRUNTIME_AVAILABLE
void MainWindow::on_loadModel_clicked()
{
QString dir = m_imgDir.isEmpty() ? QDir::currentPath() : m_imgDir;
QString modelPath = QFileDialog::getOpenFileName(
this, tr("Open YOLO ONNX Model"), dir,
tr("ONNX Models (*.onnx)"));
if (modelPath.isEmpty()) return;
loadOnnxModel(modelPath);
}
void MainWindow::loadOnnxModel(const QString& modelPath)
{
QApplication::setOverrideCursor(Qt::WaitCursor);
std::string errorMsg;
bool ok = m_detector.loadModel(modelPath.toStdString(), errorMsg);
QApplication::restoreOverrideCursor();
if (ok) {
QString versionStr;
switch (m_detector.getVersion()) {
case YoloVersion::V5: versionStr = "YOLOv5"; break;
case YoloVersion::V8: versionStr = "YOLOv8"; break;
case YoloVersion::V11: versionStr = "YOLO11"; break;
case YoloVersion::V12: versionStr = "YOLO12"; break;
case YoloVersion::V26: versionStr = "YOLOv26"; break;
default: versionStr = "YOLO"; break;
}
if (m_detector.isEndToEnd()) versionStr += " (end2end)";
m_labelModelStatus->setText(
QString("%1 | %2 classes | %3x%4 | %5")
.arg(QFileInfo(modelPath).fileName())
.arg(m_detector.getNumClasses())
.arg(m_detector.getInputWidth())
.arg(m_detector.getInputHeight())
.arg(versionStr));
// Class list handling
const auto& modelClasses = m_detector.getClassNames();
if (!modelClasses.empty() && m_objList.isEmpty()) {
// No user classes loaded — auto-populate from model
loadClassesFromModel();
} else if (!modelClasses.empty() && !m_objList.isEmpty()) {
// Both exist — check if they match
bool mismatch = false;
if (static_cast<int>(modelClasses.size()) != m_objList.size()) {
mismatch = true;
} else {
int idx = 0;
for (const auto& pair : modelClasses) {
if (QString::fromStdString(pair.second) != m_objList.at(idx)) {
mismatch = true;
break;
}
idx++;
}
}
if (mismatch) {
pjreddie_style_msgBox(QMessageBox::Warning, "Class Mismatch",
QString("The loaded class list (%1 classes) does not match "
"the model's class list (%2 classes).\n\n"
"Auto-labeling is disabled to prevent incorrect labels.\n"
"Either load a matching class file or re-load the model "
"without a class file to use the model's built-in classes.")
.arg(m_objList.size())
.arg(modelClasses.size()));
m_btnAutoLabel->setEnabled(false);
m_btnAutoLabelAll->setEnabled(false);
m_labelModelStatus->setText(m_labelModelStatus->text() + " | CLASS MISMATCH");
return;
}
}
bool hasImages = !m_imgList.isEmpty();
m_btnAutoLabel->setEnabled(hasImages);
m_btnAutoLabelAll->setEnabled(hasImages);
} else {
pjreddie_style_msgBox(QMessageBox::Critical, "Error",
QString("Failed to load model:\n%1").arg(QString::fromStdString(errorMsg)));
m_labelModelStatus->setText("Load failed");
}
}
void MainWindow::loadClassesFromModel()
{
const auto& classNames = m_detector.getClassNames();
if (classNames.empty()) return;
// Clear existing table
while (ui->tableWidget_label->rowCount() > 0)
ui->tableWidget_label->removeRow(0);
m_objList.clear();
ui->label_image->m_drawObjectBoxColor.clear();
// Populate from model metadata (same pattern as load_label_list_data)
int fileIndex = 0;
for (const auto& pair : classNames) {
int nRow = ui->tableWidget_label->rowCount();
QString qstrLabel = QString::fromStdString(pair.second);
QColor labelColor = label_img::BOX_COLORS[(fileIndex++) % 10];
m_objList << qstrLabel;
ui->tableWidget_label->insertRow(nRow);
ui->tableWidget_label->setItem(nRow, 0, new QTableWidgetItem(qstrLabel));
ui->tableWidget_label->item(nRow, 0)->setFlags(
ui->tableWidget_label->item(nRow, 0)->flags() ^ Qt::ItemIsEditable);
ui->tableWidget_label->setItem(nRow, 1, new QTableWidgetItem(QString()));
ui->tableWidget_label->item(nRow, 1)->setBackground(labelColor);
ui->tableWidget_label->item(nRow, 1)->setFlags(
ui->tableWidget_label->item(nRow, 1)->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
ui->label_image->m_drawObjectBoxColor.push_back(labelColor);
}
ui->label_image->m_objList = m_objList;
if (!m_objList.isEmpty()) {
set_label(0);
}
}
void MainWindow::on_autoLabel_clicked()
{
if (!m_detector.isLoaded() || !ui->label_image->isOpened()) return;
QImage img = ui->label_image->getInputImage();
if (img.isNull()) return;
QApplication::setOverrideCursor(Qt::WaitCursor);