-
Notifications
You must be signed in to change notification settings - Fork 34
/
TagLab.py
5829 lines (4489 loc) · 216 KB
/
TagLab.py
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
#!/usr/bin/python3
# # TagLab
# A semi-automatic segmentation tool
#
# Copyright(C) 2019
# Visual Computing Lab
# ISTI - Italian National Research Council
# All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
# for more details.
import sys
import os
import datetime
import shutil
import json
import numpy as np
import urllib
import platform
import pandas as pd
import importlib
from PyQt5.QtCore import Qt, QSize, QMargins, QDir, QPoint, QPointF, QRectF, QTimer, pyqtSlot, pyqtSignal, QSettings, QFileInfo, QModelIndex
from PyQt5.QtGui import QFontDatabase, QFont, QPixmap, QIcon, QKeySequence, QPen, QImageReader, QImage
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QFileDialog, QComboBox, QMenuBar, QMenu, QSizePolicy, QScrollArea, \
QLabel, QToolButton, QPushButton, QSlider, QCheckBox, \
QMessageBox, QGroupBox, QLayout, QHBoxLayout, QVBoxLayout, QFrame, QDockWidget, QTextEdit, QAction
import pprint
# PYTORCH
from source.QtAlignmentToolWidget import QtAlignmentToolWidget
try:
import torch
from torch.nn.functional import upsample
except Exception as e:
print("Incompatible version between pytorch, cuda and python.\n" +
"Knowing working version combinations are\n: Cuda 10.0, pytorch 1.0.0, python 3.6.8" + str(e))
# exit()
# CUSTOM
import csv
import source.Mask as Mask
import source.RasterOps as rasterops
from source.QtImageViewerPlus import QtImageViewerPlus
from source.QtMapViewer import QtMapViewer
from source.QtSettingsWidget import QtSettingsWidget
from source.QtMapSettingsWidget import QtMapSettingsWidget
from source.QtScaleWidget import QtScaleWidget
from source.QtWorkingAreaWidget import QtWorkingAreaWidget
from source.QtCropWidget import QtCropWidget
from source.QtLayersWidget import QtLayersWidget
from source.QtHelpWidget import QtHelpWidget
from source.QtMessages import QtMessageWidget
from source.QtProgressBarCustom import QtProgressBarCustom
from source.QtHistogramWidget import QtHistogramWidget
from source.QtClassifierWidget import QtClassifierWidget
from source.QtNewDatasetWidget import QtNewDatasetWidget
from source.QtSampleWidget import QtSampleWidget
from source.QtTrainingResultsWidget import QtTrainingResultsWidget
from source.QtTYNWidget import QtTYNWidget
from source.QtComparePanel import QtComparePanel
from source.QtTablePanel import QtTablePanel
from source.QtExportAnnAsTable import QtExportAnnAsTable
from source.QtTableLabel import QtTableLabel
from source.QtProjectWidget import QtProjectWidget
from source.QtProjectEditor import QtProjectEditor
from source.Project import Project, loadProject
from source.Point import Point
from source.Image import Image
from source.MapClassifier import MapClassifier
from source.NewDataset import NewDataset
from source.QtGridWidget import QtGridWidget
from source.QtDictionaryWidget import QtDictionaryWidget
from source.QtRegionAttributesWidget import QtRegionAttributesWidget
from source.QtShapefileAttributeWidget import QtAttributeWidget
# from source.QtDXFfileAttributeWidget import QtDXFExportWidget
import ezdxf
from ezdxf.enums import TextEntityAlignment
from ezdxf.entities import Layer
import math
from source.QtPanelInfo import QtPanelInfo
from source.Sampler import Sampler
from source.QtImportViscoreWidget import QtImportViscoreWidget
from source.QtCoralNetToolboxWidget import QtCoralNetToolboxWidget
from source.QtExportCoralNetDataWidget import QtExportCoralNetDataWidget
from source import genutils
from source.Blob import Blob
from source.Shape import Layer, Shape
from source.Tools import Tools
# training modules
from models.coral_dataset import CoralsDataset
import models.training as training
# LOGGING
import logging
# configure the logger
now = datetime.datetime.now()
#LOG_FILENAME = "tool" + now.strftime("%Y-%m-%d-%H-%M") + ".log"
LOG_FILENAME = "TagLab.log"
logging.basicConfig(level=logging.DEBUG, filemode='w', filename=LOG_FILENAME, format = '%(asctime)s %(levelname)-8s %(message)s')
logfile = logging.getLogger("tool-logger")
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
pass
def closeEvent(self, event):
taglab = self.centralWidget()
if taglab.project.filename is not None:
box = QMessageBox()
reply = box.question(self, taglab.TAGLAB_VERSION, "Do you want to save changes to " + taglab.project.filename,
QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
taglab.saveProject()
if reply == QMessageBox.Cancel:
event.ignore()
return
super(MainWindow, self).closeEvent(event)
class TagLab(QMainWindow):
def __init__(self, screen_size, parent=None):
super(TagLab, self).__init__(parent)
##### CUSTOM STYLE #####
self.setStyleSheet("background-color: rgb(55,55,55); color: white")
current_version, need_to_update = self.checkNewVersion()
if need_to_update:
print("This is a new version available! Please, launch update.py and then install.py (for the version of 29th October 2024 only).")
sys.exit(0)
##### DATA INITIALIZATION AND SETUP #####
self.taglab_dir = os.path.dirname(__file__)
self.TAGLAB_VERSION = "TagLab " + current_version
print(self.TAGLAB_VERSION)
# SETTINGS
self.settings_widget = QtSettingsWidget(self.taglab_dir)
# LOAD CONFIGURATION FILE
f = open(os.path.join(self.taglab_dir, "config.json"), "r")
config_dict = json.load(f)
self.available_classifiers = config_dict["Available Classifiers"]
logfile.info("[INFO] Initizialization begins..")
self.project = Project() # current project
self.last_image_loaded = None
self.map_3D_filename = None #refactor THIS!
self.map_image_filename = None #"map.png" #REFACTOR to project.map_filename
self.map_acquisition_date = None #"YYYY-MM-DD"
self.recentFileActs = [] #refactor to self.maxRecentProjects
self.maxRecentFiles = 4 #refactor to maxRecentProjects
self.separatorRecentFilesAct = None #refactor to separatorRecentFiles
##### INTERFACE #####
#####################
self.mapWidget = None
self.projectEditor = None
self.align_tool_widget = None
self.edit_project_widget = None
self.sample_point_widget = None
self.scale_widget = None
self.dictionary_widget = None
self.working_area_widget = None
self.dataset_train_info = None
self.region_attributes_widget = None
self.crop_widget = None
self.classifierWidget = None
self.newDatasetWidget = None
self.help_widget = None
#message widget for help
self.message_widget = None
self.trainYourNetworkWidget = None
self.trainResultsWidget = None
self.progress_bar = None
self.gridWidget = None
self.contextMenuPosition = None
##### TOP LAYOUT
##### LAYOUT EDITING TOOLS (VERTICAL)
flatbuttonstyle = """
QPushButton:checked { background-color: rgb(100,100,100); }
QPushButton:hover { border: 1px solid darkgray; }
QToolTip { background-color: white; color: rgb(100,100,100); }
"""
flatbuttonstyle_red = """
QPushButton:checked { background-color: rgb(100,100,100); }
QPushButton:hover { border: 1px solid rgb(255,100,100); }
QToolTip { background-color: white; color: rgb(100,100,100); }
"""
self.btnMove = self.newButton("move.png", "Pan/Zoom", flatbuttonstyle, self.move)
self.btnPoint = self.newButton("point.png", "Place annotation point", flatbuttonstyle, self.placeAnnPoint)
self.btnFreehand = self.newButton("pencil.png", "Freehand segmentation", flatbuttonstyle, self.freehandSegmentation)
self.btnCreateCrack = self.newButton("crack.png", "Create crack", flatbuttonstyle, self.createCrack)
self.btnWatershed = self.newButton("watershed.png", "Watershed segmentation", flatbuttonstyle, self.watershedSegmentation)
self.btnBricksSegmentation = self.newButton("brick.png", "Bricks segmentation", flatbuttonstyle, self.bricksSegmentation)
self.btnSamInteractive = self.newButton("saminteractive2.png", "SAM - positive/negative clicks in an area", flatbuttonstyle, self.saminteractive)
self.btnSam = self.newButton("sam.png", "SAM - all instances in an area", flatbuttonstyle, self.sam)
self.btnFourClicks = self.newButton("dexter.png", "4-clicks segmentation", flatbuttonstyle, self.fourClicks)
self.btnRitm = self.newButton("ritm.png", "Positive/negative clicks segmentation", flatbuttonstyle, self.ritm)
self.btnAssign = self.newButton("bucket.png", "Assign class to region", flatbuttonstyle, self.assign)
self.btnEditBorder = self.newButton("edit.png", "Edit region border", flatbuttonstyle, self.editBorder)
self.btnCut = self.newButton("scissors.png", "Cut region", flatbuttonstyle, self.cut)
self.btnRuler = self.newButton("ruler.png", "Measure tool", flatbuttonstyle, self.ruler)
# Split blob operation removed from the toolbar
# self.btnSplitBlob = self.newButton("split.png", "Split Blob", flatbuttonstyle1, self.splitBlob)
self.btnAutoClassification = self.newButton("auto.png", "Fully auto semantic segmentation", flatbuttonstyle, self.selectClassifier)
self.btnCreateGrid = self.newButton("grid.png", "Create grid", flatbuttonstyle, self.createGrid)
self.btnGrid = self.newButton("grid-edit.png", "Active/disactive grid operations", flatbuttonstyle, self.toggleGrid)
self.btnSplitScreen = self.newButton("split.png", "Split screen", flatbuttonstyle, self.toggleComparison)
self.btnAutoMatch = self.newButton("automatch.png", "Compute automatic matches", flatbuttonstyle, self.autoCorrespondences)
self.btnAutoMatch.setCheckable(False) # WARNING: Automatic matches button is not checkable
self.btnMatch = self.newButton("manualmatch.png", "Edit matches ", flatbuttonstyle, self.matchTool)
# separator
pxmapSeparator = QPixmap("icons/separator.png")
labelSeparator1 = QLabel()
labelSeparator1.setPixmap(pxmapSeparator.scaled(QSize(35, 30)))
labelSeparator2 = QLabel()
labelSeparator2.setPixmap(pxmapSeparator.scaled(QSize(35, 30)))
labelSeparator3 = QLabel()
labelSeparator3.setPixmap(pxmapSeparator.scaled(QSize(35, 30)))
labelSeparator4 = QLabel()
labelSeparator4.setPixmap(pxmapSeparator.scaled(QSize(35, 30)))
"""
separatorLine = QFrame()
separatorLine.setFrameShape(QFrame.HLine)
separatorLine.setFrameShadow(QFrame.Raised)
separatorLine.setLineWidth(3)
"""
#filling the layout
layout_tools = QVBoxLayout()
layout_tools.setSpacing(0)
layout_tools.addWidget(self.btnMove)
layout_tools.addWidget(self.btnPoint)
layout_tools.addWidget(self.btnFourClicks)
layout_tools.addWidget(self.btnRitm)
layout_tools.addWidget(self.btnFreehand)
layout_tools.addWidget(self.btnWatershed)
#layout_tools.addWidget(self.btnBricksSegmentation)
layout_tools.addWidget(self.btnSam)
layout_tools.addWidget(self.btnSamInteractive)
layout_tools.addWidget(labelSeparator1) #separator-----------------------------------
layout_tools.addWidget(self.btnAssign)
layout_tools.addWidget(self.btnEditBorder)
layout_tools.addWidget(self.btnCut)
#layout_tools.addWidget(self.btnCreateCrack)
layout_tools.addWidget(self.btnRuler)
layout_tools.addWidget(labelSeparator2) #separator-----------------------------------
layout_tools.addWidget(self.btnAutoClassification)
layout_tools.addWidget(labelSeparator3) #separator-----------------------------------
layout_tools.addWidget(self.btnCreateGrid)
layout_tools.addWidget(self.btnGrid)
layout_tools.addWidget(labelSeparator4) #separator-----------------------------------
layout_tools.addWidget(self.btnSplitScreen)
layout_tools.addWidget(self.btnAutoMatch)
layout_tools.addWidget(self.btnMatch)
layout_tools.addStretch()
# CONTEXT MENU ACTIONS
self.markEmpty = self.newAction("Mark cell as empty", "", self.markEmptyOperation)
self.markIncomplete = self.newAction("Mark cell as incomplete", "", self.markIncompleteOperation)
self.markComplete = self.newAction("Mark cell as complete", "", self.markCompleteOperation)
self.addNote = self.newAction("Add/edit note", "", self.addNoteOperation)
self.assignAction = self.newAction("Assign Class to Region", "A", self.assignOperation)
self.deleteAction = self.newAction("Delete Region", "Del", self.deleteSelectedBlobs)
self.mergeAction = self.newAction("Merge Overlapping Regions", "M", self.union)
self.divideAction = self.newAction("Divide Regions", "D", self.divide)
self.subtractAction = self.newAction("Subtract Regions", "S", self.subtract)
self.refineAction = self.newAction("Refine Border", "R", self.refineBorderOperation)
self.refineAllAction = self.newAction("Refine All Borders", "", self.refineBorderAll)
self.dilateAction = self.newAction("Dilate Border", "+", self.dilate)
self.erodeAction = self.newAction("Erode Border", "-", self.erode)
self.attachBoundariesAction = self.newAction("Snap Borders", "B", self.attachBoundaries)
self.fillAction = self.newAction("Fill Region", "F", self.fillLabel)
self.createNegative = self.newAction("Create a Background Region using the WA", "N", self.createNegative)
# VIEWERPLUS
# main viewer
self.viewerplus = QtImageViewerPlus(self.taglab_dir)
self.viewerplus.logfile = logfile
self.viewerplus.viewUpdated.connect(self.updateViewInfo)
self.viewerplus.activated.connect(self.setActiveViewer)
self.viewerplus.updateInfoPanel.connect(self.updatePanelInfo)
self.viewerplus.activeImageChanged[Image].connect(self.setActiveImage)
self.viewerplus.mouseMoved[float, float].connect(self.updateMousePos)
self.viewerplus.selectionChanged.connect(self.updateEditActions)
self.viewerplus.selectionReset.connect(self.resetPanelInfo)
# secondary viewer in SPLIT MODE
self.viewerplus2 = QtImageViewerPlus(self.taglab_dir)
self.viewerplus2.logfile = logfile
self.viewerplus2.viewUpdated.connect(self.updateViewInfo)
self.viewerplus2.activated.connect(self.setActiveViewer)
self.viewerplus2.updateInfoPanel.connect(self.updatePanelInfo)
self.viewerplus2.mouseMoved[float, float].connect(self.updateMousePos)
self.viewerplus2.selectionChanged.connect(self.updateEditActions)
self.viewerplus2.selectionReset.connect(self.resetPanelInfo)
self.viewerplus.newSelection.connect(self.showMatch)
self.viewerplus2.newSelection.connect(self.showMatch)
self.viewerplus.newSelection.connect(self.showBlobOnTable)
self.viewerplus.newSelectionPoint.connect(self.showPointOnTable)
# SAM-related tool connections
#self.viewerplus.tools.tools["SAM"].samEnded.connect(self.resetSam)
#self.viewerplus2.tools.tools["SAM"].samEnded.connect(self.resetSam)
# tool info messages
# self.viewerplus.tools.tools["SAM"].tool_message.connect(self.message)
# self.viewerplus.tools.tools["WATERSHED"].tool_message.connect(self.message)
self.viewerplus.tools.tool_mess.connect(self.message)
# last activated viewerplus: redirect here context menu commands and keyboard commands
self.activeviewer = None
self.inactiveviewer = None
###### LAYOUT MAIN VIEW
self.comboboxSourceImage = QComboBox()
self.comboboxSourceImage.setMinimumWidth(200)
self.comboboxTargetImage = QComboBox()
self.comboboxTargetImage.setMinimumWidth(200)
self.comboboxSourceImage.currentIndexChanged.connect(self.sourceImageChanged)
self.comboboxTargetImage.currentIndexChanged.connect(self.targetImageChanged)
self.lblSlider = QLabel("Transparency: 0%")
self.sliderTransparency = QSlider(Qt.Horizontal)
self.sliderTransparency.setFocusPolicy(Qt.StrongFocus)
self.sliderTransparency.setMinimumWidth(200)
self.sliderTransparency.setStyleSheet(slider_style2)
self.sliderTransparency.setMinimum(0)
self.sliderTransparency.setMaximum(100)
self.sliderTransparency.setValue(0)
self.sliderTransparency.setTickInterval(10)
self.sliderTransparency.valueChanged[int].connect(self.sliderTransparencyChanged)
self.checkBoxFill = QCheckBox("Fill")
self.checkBoxFill.setChecked(True)
self.checkBoxFill.setFocusPolicy(Qt.NoFocus)
self.checkBoxFill.setMinimumWidth(60)
self.checkBoxFill.stateChanged[int].connect(self.viewerplus.toggleFill)
self.checkBoxFill.stateChanged[int].connect(self.viewerplus2.toggleFill)
self.checkBoxFill.stateChanged[int].connect(self.saveGuiPreferences)
self.checkBoxBorders = QCheckBox("Boundaries")
self.checkBoxBorders.setChecked(True)
self.checkBoxBorders.setFocusPolicy(Qt.NoFocus)
self.checkBoxBorders.setMinimumWidth(120)
self.checkBoxBorders.stateChanged[int].connect(self.viewerplus.toggleBorders)
self.checkBoxBorders.stateChanged[int].connect(self.viewerplus2.toggleBorders)
self.checkBoxBorders.stateChanged[int].connect(self.saveGuiPreferences)
self.checkBoxIds = QCheckBox("Ids")
self.checkBoxIds.setChecked(True)
self.checkBoxIds.setFocusPolicy(Qt.NoFocus)
self.checkBoxIds.setMinimumWidth(60)
self.checkBoxIds.stateChanged[int].connect(self.viewerplus.toggleIds)
self.checkBoxIds.stateChanged[int].connect(self.viewerplus2.toggleIds)
self.checkBoxIds.stateChanged[int].connect(self.saveGuiPreferences)
self.checkBoxGrid = QCheckBox("Grid")
self.checkBoxGrid.setMinimumWidth(60)
self.checkBoxGrid.setFocusPolicy(Qt.NoFocus)
self.checkBoxGrid.stateChanged[int].connect(self.viewerplus.toggleGrid)
self.checkBoxGrid.stateChanged[int].connect(self.viewerplus2.toggleGrid)
self.checkBoxGrid.stateChanged[int].connect(self.saveGuiPreferences)
self.labelZoom = QLabel("Zoom:")
self.labelMouseLeft = QLabel("x:")
self.labelMouseTop = QLabel("y:")
self.labelZoomInfo = QLabel("100%")
self.labelMouseLeftInfo = QLabel("0")
self.labelMouseTopInfo = QLabel("0")
self.labelZoomInfo.setMinimumWidth(70)
self.labelMouseLeftInfo.setMinimumWidth(70)
self.labelMouseTopInfo.setMinimumWidth(70)
layout_header = QHBoxLayout()
layout_header.addWidget(QLabel("Map: "))
layout_header.addWidget(self.comboboxSourceImage)
layout_header.addWidget(self.comboboxTargetImage)
layout_header.addStretch()
layout_header.addWidget(self.lblSlider)
layout_header.addWidget(self.sliderTransparency)
layout_header.addStretch()
layout_header.addWidget(self.checkBoxFill)
layout_header.addWidget(self.checkBoxBorders)
layout_header.addWidget(self.checkBoxIds)
layout_header.addWidget(self.checkBoxGrid)
layout_header.addStretch()
layout_header.addWidget(self.labelZoom)
layout_header.addWidget(self.labelZoomInfo)
layout_header.addWidget(self.labelMouseLeft)
layout_header.addWidget(self.labelMouseLeftInfo)
layout_header.addWidget(self.labelMouseTop)
layout_header.addWidget(self.labelMouseTopInfo)
layout_viewers = QHBoxLayout()
layout_viewers.addWidget(self.viewerplus)
layout_viewers.addWidget(self.viewerplus2)
layout_viewers.setStretchFactor(self.viewerplus, 1)
layout_viewers.setStretchFactor(self.viewerplus2, 1)
layout_main_view = QVBoxLayout()
layout_main_view.setSpacing(1)
layout_main_view.addLayout(layout_header)
layout_main_view.addLayout(layout_viewers)
##### LAYOUT - labels + blob info + navigation map
# LAYERS PANEL
self.layers_widget = QtLayersWidget()
self.layers_widget.setProject(self.project)
self.layers_widget.showImage.connect(self.showImage)
self.layers_widget.toggleLayer.connect(self.toggleLayer)
self.layers_widget.toggleAnnotations.connect(self.toggleAnnotations)
self.layers_widget.deleteLayer.connect(self.deleteLayer)
# LABELS PANEL
self.labels_widget = QtTableLabel()
try:
default_dict = "dictionaries/scripps.json"
self.default_dictionary = self.settings_widget.settings.value("default-dictionary",
defaultValue=default_dict,
type=str)
# Check if previously stored dict actually exists
if not os.path.exists(self.default_dictionary):
QMessageBox.warning(self,
"Warning",
f"Previously loaded dictionary {self.default_dictionary} not found! "
f"Attempting to load TagLab default {default_dict} instead.")
# If not, check for the scripps dictionary
self.default_dictionary = default_dict
if not os.path.exists(self.default_dictionary):
raise Exception(f"TagLab default dictionary {self.default_dictionary} not found! "
f"Please re-download it.")
# Re-set the default dictionary
self.settings_widget.settings.setValue("default-dictionary", self.default_dictionary)
# Load the dictionary, load the project
self.project.loadDictionary(self.default_dictionary)
self.labels_widget.setLabels(self.project, None)
except Exception as e:
# If neither exist, then open TagLab w/o a dict, and user can reset within
QMessageBox.critical(self, "Error", str(e))
groupbox_style = "QGroupBox\
{\
border: 2px solid rgb(40,40,40);\
border-radius: 0px;\
margin-top: 10px;\
margin-left: 0px;\
margin-right: 0px;\
padding-top: 5px;\
padding-left: 5px;\
padding-bottom: 5px;\
padding-right: 5px;\
}\
\
QGroupBox::title\
{\
subcontrol-origin: margin;\
subcontrol-position: top center;\
padding: 0 0px;\
}"
self.groupbox_labels = QGroupBox()
self.groupbox_labels.setStyleSheet("border: 2px solid rgb(255,40,40); padding: 0px;")
layout_groupbox = QVBoxLayout()
layout_groupbox.addWidget(self.labels_widget)
self.groupbox_labels.setLayout(layout_groupbox)
# COMPARE PANEL
self.compare_panel = QtComparePanel()
self.compare_panel.filterChanged[str].connect(self.updateVisibleMatches)
self.compare_panel.areaModeChanged[str].connect(self.updateAreaMode)
self.compare_panel.data_table.clicked.connect(self.showConnectionCluster)
# SINGLE-VIEW DATA PANEL
self.data_panel = QtTablePanel()
self.data_panel.selectionChanged.connect(self.showOnViewer)
self.data_panel.selectionChanged.connect(self.updatePanelInfoSelected)
self.groupbox_comparison = QGroupBox()
layout_groupbox2 = QVBoxLayout()
# in single view only show the table panel
layout_groupbox2.addWidget(self.data_panel)
self.compare_panel.hide()
layout_groupbox2.addWidget(self.compare_panel)
layout_groupbox2.setContentsMargins(QMargins(0, 0, 0, 0))
self.groupbox_comparison.setLayout(layout_groupbox2)
# BLOB INFO
self.groupbox_blobpanel = QtPanelInfo(self.project.region_attributes, self.project.labels)
self.blob_with_info_displayed = None
# MAP VIEWER
self.mapviewer = QtMapViewer(350)
self.mapviewer.setMinimumHeight(200)
self.mapviewer.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.MinimumExpanding)
self.viewerplus.viewUpdated[QRectF].connect(self.mapviewer.drawOverlayImage)
self.mapviewer.leftMouseButtonPressed[float, float].connect(self.viewerplus.center)
self.mapviewer.mouseMoveLeftPressed[float, float].connect(self.viewerplus.center)
self.mapviewer.setStyleSheet("background-color: rgb(40,40,40); border:none")
self.viewerplus2.viewUpdated[QRectF].connect(self.mapviewer.drawOverlayImage)
# DOCK
panels_size = int(screen_size.width() * 0.22)
if panels_size > 900:
panels_size = 900
if panels_size < 500:
panels_size = 500
self.layersdock = QDockWidget("Layers", self)
self.layersdock.setWidget(self.layers_widget)
self.layers_widget.setMinimumWidth(panels_size)
self.layers_widget.setStyleSheet("padding: 0px")
self.layersdock.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
self.labelsdock = QDockWidget("Labels", self)
self.groupbox_labels.setMinimumWidth(panels_size)
self.labelsdock.setWidget(self.groupbox_labels)
self.groupbox_labels.setStyleSheet("padding: 0px")
self.datadock = QDockWidget("Data Table", self)
self.groupbox_comparison.setMinimumWidth(panels_size)
self.datadock.setWidget(self.groupbox_comparison)
self.groupbox_comparison.setStyleSheet("padding: 0px")
self.blobdock = QDockWidget("Info and Attributes", self)
self.groupbox_blobpanel.setMinimumWidth(panels_size)
self.blobdock.setWidget(self.groupbox_blobpanel)
self.mapdock = QDockWidget("Map Preview", self)
self.mapviewer.preferred = panels_size
self.mapviewer.setMinimumWidth(panels_size)
self.mapdock.setWidget(self.mapviewer)
self.mapdock.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.MinimumExpanding)
for dock in (self.labelsdock, self.layersdock, self.datadock, self.blobdock, self.mapdock):
dock.setAllowedAreas(Qt.RightDockWidgetArea)
self.addDockWidget(Qt.RightDockWidgetArea, dock)
self.setDockOptions(self.AnimatedDocks)
self.compare_panel.setMinimumHeight(200)
##### MAIN LAYOUT
central_widget_layout = QHBoxLayout()
central_widget_layout.addLayout(layout_tools)
central_widget_layout.addLayout(layout_main_view)
# Add message widget to the central layout
if self.message_widget is not None:
central_widget_layout.addWidget(self.message_widget)
# central_widget_layout.addLayout(self.message_widget.layout)
self.central_widget = QWidget()
self.central_widget.setLayout(central_widget_layout)
self.setCentralWidget(self.central_widget)
self.filemenu = None
self.submenuWorkingArea = None
self.submenuExport = None
self.submenuImport = None
self.regionmenu = None
self.comparemenu = None
self.demmenu = None
self.helpmenu = None
self.setMenuBar(self.createMenuBar())
self.setProjectTitle("NONE")
##### FURTHER INITIALIZAION #####
#################################
# CHECK SEGMENT_ANYTHING AVAILABILITY
self.SAM_is_available = True
if importlib.util.find_spec("segment_anything") is None:
print("Segment Anything (SAM) is not installed -> Sam generator tool will be not available.")
self.SAM_is_available = False
self.btnSam.setVisible(False)
self.btnSamInteractive.setVisible(False)
# set default opacity
self.sliderTransparency.setValue(50)
self.transparency_value = 0.5
# EVENTS-CONNECTIONS
self.settings_widget.general_settings.researchFieldChanged[str].connect(self.researchFieldChanged)
# self.settings_widget.general_settings.autosaveInfoChanged[int].connect(self.setAutosave)
self.settings_widget.general_settings.autosaveInfoChanged[int].connect(self.setAutosave)
self.settings_widget.drawing_settings.borderPenChanged[str, int].connect(self.viewerplus.setBorderPen)
self.settings_widget.drawing_settings.selectionPenChanged[str, int].connect(self.viewerplus.setSelectionPen)
self.settings_widget.drawing_settings.workingAreaPenChanged[str, int].connect(self.viewerplus.setWorkingAreaPen)
self.settings_widget.drawing_settings.borderPenChanged[str, int].connect(self.viewerplus2.setBorderPen)
self.settings_widget.drawing_settings.selectionPenChanged[str, int].connect(self.viewerplus2.setSelectionPen)
self.settings_widget.drawing_settings.workingAreaPenChanged[str, int].connect(self.viewerplus2.setWorkingAreaPen)
self.connectLabelsPanelWithViewers()
self.connectProject()
self.viewerplus.viewHasChanged[float, float, float].connect(self.viewerplus2.setViewParameters)
self.viewerplus2.viewHasChanged[float, float, float].connect(self.viewerplus.setViewParameters)
self.viewerplus.customContextMenuRequested.connect(self.openContextMenu)
self.viewerplus2.customContextMenuRequested.connect(self.openContextMenu)
self.settings_widget.loadSettings()
# SWITCH IMAGES
self.current_image_index = 0
# menu options
self.mapActionList = []
self.image2update = None
# training results
self.classifier_name = None
self.network_name = None
self.dataset_train = None
# NETWORKS
self.classifier = None
# a dirty trick to adjust all the size..
self.showMinimized()
self.showMaximized()
logfile.info("[INFO] Inizialization finished!")
# autosave timer
self.timer = QTimer(self)
self.updateToolStatus()
self.split_screen_flag = False
self.update_panels_flag = True
self.disableSplitScreen()
self.setGuiPreferences()
self.move()
def toggleHeritageButtons(self, show=False):
"""
Shows or hides segmentation buttons based on the 'show' parameter.
:param show: If True, buttons will be shown; if False, buttons will be hidden
"""
self.btnWatershed.setVisible(show)
self.importViscorePointsAct.setVisible(not show)
self.importCoralNetPointsAct.setVisible(not show)
self.exportCoralNetPointsAct.setVisible(not show)
self.exportCoralNetDataAct.setVisible(not show)
self.openCoralNetToolboxAct.setVisible(not show)
def setGuiPreferences(self):
settings = QSettings("VCLAB", "TagLab")
value = settings.value("gui-checkbox-fill", type=bool, defaultValue=True)
self.checkBoxFill.setChecked(value)
value = settings.value("gui-checkbox-borders", type=bool, defaultValue=True)
self.checkBoxBorders.setChecked(value)
value = settings.value("gui-checkbox-ids", type=bool, defaultValue=True)
self.checkBoxGrid.setChecked(value)
value = settings.value("gui-checkbox-grid", type=bool, defaultValue=False)
self.checkBoxIds.setChecked(value)
@pyqtSlot()
def saveGuiPreferences(self):
settings = QSettings("VCLAB", "TagLab")
settings.setValue("gui-checkbox-fill", self.checkBoxFill.isChecked())
settings.setValue("gui-checkbox-borders", self.checkBoxBorders.isChecked())
settings.setValue("gui-checkbox-ids", self.checkBoxIds.isChecked())
settings.setValue("gui-checkbox-grid", self.checkBoxGrid.isChecked())
def checkNewVersion(self):
github_repo = 'cnr-isti-vclab/TagLab/'
base_repo = 'https://github.com/' + github_repo
raw_link = 'https://raw.githubusercontent.com/' + github_repo + 'main/TAGLAB_VERSION'
# read offline version
taglab_version_file = os.path.join(os.path.dirname(__file__), "TAGLAB_VERSION")
f_off_version = open(taglab_version_file, "r")
taglab_offline_version = f_off_version.read()
#print('Raw link: ' + raw_link)
try:
f_online_version = urllib.request.urlopen(raw_link)
except:
return taglab_offline_version, False
taglab_online_version = f_online_version.read().decode('utf-8')
offline_spl_version = taglab_offline_version.split('.')
online_spl_version = taglab_online_version.split('.')
#print('offline: ' + str(offline_spl_version))
#print('online: ' + str(online_spl_version))
# Check if I need to update TagLab
need_to_update = False
i = 0
while i < len(online_spl_version) and not need_to_update:
if (not (i < len(offline_spl_version))):
need_to_update = True
else:
if (int(online_spl_version[i]) > int(offline_spl_version[i])):
need_to_update = True
elif (int(online_spl_version[i]) < int(offline_spl_version[i])):
need_to_update = False
break
i = i + 1
return taglab_offline_version, need_to_update
#just to make the code less verbose
def newAction(self, text, shortcut, callback):
action = QAction(text, self)
if shortcut != "":
action.setShortcut(QKeySequence(shortcut))
#compatibility with Qt < 5.10
if hasattr(action, 'setShortcutVisibleInContextMenu'):
action.setShortcutVisibleInContextMenu(True)
action.triggered.connect(callback)
return action
def newButton(self, icon, tooltip, style, callback):
#ICON_SIZE = 48
ICON_SIZE = 35
BUTTON_SIZE = 35
button = QPushButton()
button.setEnabled(True)
button.setCheckable(True)
button.setFlat(True)
button.setStyleSheet(style)
button.setMinimumWidth(ICON_SIZE)
button.setMinimumHeight(ICON_SIZE)
button.setIcon(QIcon(os.path.join(os.path.join(self.taglab_dir, "icons"), icon)))
button.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
button.setMaximumWidth(BUTTON_SIZE)
button.setToolTip(tooltip)
button.clicked.connect(callback)
return button
@pyqtSlot()
def updateEditActions(self):
if self.btnGrid.isChecked():
self.markEmpty.setVisible(True)
self.markComplete.setVisible(True)
self.markIncomplete.setVisible(True)
self.addNote.setVisible(True)
else:
self.markEmpty.setVisible(False)
self.markComplete.setVisible(False)
self.markIncomplete.setVisible(False)
self.addNote.setVisible(False)
nSelected = len(self.viewerplus.selected_blobs) + len(self.viewerplus2.selected_blobs)
self.assignAction.setEnabled(nSelected > 0)
self.deleteAction.setEnabled(nSelected > 0)
self.mergeAction.setEnabled(nSelected > 1)
self.divideAction.setEnabled(nSelected > 1)
self.subtractAction.setEnabled(nSelected > 1)
self.refineAction.setEnabled(nSelected == 1)
self.dilateAction.setEnabled(nSelected > 0)
self.erodeAction.setEnabled(nSelected > 0)
self.attachBoundariesAction.setEnabled(nSelected == 2)
self.fillAction.setEnabled(nSelected > 0)
@pyqtSlot()
def markEmptyOperation(self):
if self.contextMenuPosition is not None:
self.activeviewer.updateCellState(self.contextMenuPosition.x(),self.contextMenuPosition.y(), 0)
@pyqtSlot()
def markIncompleteOperation(self):
if self.contextMenuPosition is not None:
self.activeviewer.updateCellState(self.contextMenuPosition.x(),self.contextMenuPosition.y(), 1)
@pyqtSlot()
def markCompleteOperation(self):
if self.contextMenuPosition is not None:
self.activeviewer.updateCellState(self.contextMenuPosition.x(), self.contextMenuPosition.y(), 2)
@pyqtSlot()
def addNoteOperation(self):
if self.contextMenuPosition is not None and self.btnGrid.isChecked():
self.activeviewer.addNote(self.contextMenuPosition.x(), self.contextMenuPosition.y())
def setAutosave(self, interval):
"""
Set autosave interval. Interval is in minutes. If interval is zero or negative the autosave is disabled.
"""
if interval > 0:
# disconnect, just in case..
try:
self.timer.timeout.disconnect()
except:
pass
self.timer.timeout.connect(self.autosave)
self.timer.start(interval * 60 * 1000) # interval is in seconds
else:
self.timer.stop()
@pyqtSlot()
def autosave(self):
filename, file_extension = os.path.splitext(self.project.filename)
self.project.save(filename + "_autosave.json")
# call by pressing right button
def openContextMenu(self, position):
if len(self.project.images) == 0:
return
menu = QMenu(self)
menu.setAutoFillBackground(True)
str = "QMenu::item:selected{\
background-color: rgb(110, 110, 120);\
color: rgb(255, 255, 255);\
} QMenu::item:disabled { color:rgb(150, 150, 150); }"
menu.setStyleSheet(str)
menu.addAction(self.markEmpty)
menu.addAction(self.markIncomplete)
menu.addAction(self.markComplete)
menu.addAction(self.addNote)
menu.addSeparator()
menu.addAction(self.assignAction)
menu.addAction(self.deleteAction)
menu.addSeparator()
menu.addAction(self.mergeAction)
menu.addAction(self.divideAction)
menu.addAction(self.subtractAction)
menu.addAction(self.attachBoundariesAction)
menu.addAction(self.fillAction)
menu.addSeparator()
menu.addAction(self.refineAction)
menu.addAction(self.dilateAction)
menu.addAction(self.erodeAction)
viewer = self.sender()
self.contextMenuPosition = viewer.mapToGlobal(position)
action = menu.exec_(self.contextMenuPosition)
def setProjectTitle(self, project_name):
title = self.TAGLAB_VERSION + " [Project: " + project_name + "]"
if self.parent() is not None:
self.parent().setWindowTitle(title)
else:
self.setWindowTitle(title)
if project_name != "NONE":
settings = QSettings('VCLAB', 'TagLab')
files = settings.value('recentFileList')
if files:
try:
files.remove(project_name)
except ValueError:
pass
files.insert(0, project_name)
del files[self.maxRecentFiles:]
settings.setValue('recentFileList', files)
else:
files = []
files.append(project_name)
settings.setValue('recentFileList', files)
self.updateRecentFileActions()
def createMenuBar(self):
##### PROJECTS
newAct = QAction("New Project", self)
newAct.setShortcut('Ctrl+N')
newAct.setStatusTip("Create A New Project")
newAct.triggered.connect(self.newProject)
openAct = QAction("Open Project", self)
openAct.setShortcut('Ctrl+O')
openAct.setStatusTip("Open An Existing Project")
openAct.triggered.connect(self.openProject)
saveAct = QAction("Save Project", self)
saveAct.setShortcut('Ctrl+S')
saveAct.setStatusTip("Save Current Project")
saveAct.triggered.connect(self.saveProject)
saveAsAct = QAction("Save As", self)
saveAsAct.setShortcut('Ctrl+Alt+S')
saveAsAct.setStatusTip("Save Current Project")