-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.py
More file actions
2946 lines (2392 loc) · 122 KB
/
main.py
File metadata and controls
2946 lines (2392 loc) · 122 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
"""
Thermogram - Thermal Image Processing Application
A comprehensive application for processing and analyzing thermal images captured by DJI drones.
Provides tools for visualization, measurement, and analysis of thermal data.
Author: [email protected]
TODO:
- Allow the user to define a custom folder - OK
- Allow to import only thermal pictures - OK
- Implement 'context' dialog --> Drone info + location
- Implement save/load project folder
"""
# Qt imports
from PyQt6.QtGui import * # modified from PySide6.QtGui to PyQt6.QtGui
from PyQt6.QtWidgets import * # modified from PySide6.QtWidgets to PyQt6.QtWidgets
from PyQt6.QtCore import * # modified from PySide6.QtCore to PyQt6.QtCore
from PyQt6 import uic
# Standard library imports
import os
import json
import copy
import time
import hashlib
from pathlib import Path
from multiprocessing import freeze_support
# Custom libraries
import widgets as wid
import resources as res
import dialogs as dia
from tools import thermal_tools as tt
from tools.report_tools import create_word_report
from utils.config import config, thermal_config
from utils.logger import info, error, debug, warning
from utils.exceptions import ThermogramError, FileOperationError
_TIMING_ENABLED = str(os.environ.get("THERMOGRAM_TIMING", "")).strip().lower() in {"1", "true", "yes", "on"}
def _tlog(message: str):
if _TIMING_ENABLED:
print(f"[timing] {message}")
class _PerfTimer:
def __init__(self, label: str):
self.label = label
self.t0 = time.perf_counter()
def stop(self, extra: str = ""):
dt_ms = (time.perf_counter() - self.t0) * 1000
if extra:
_tlog(f"{self.label}: {dt_ms:.1f} ms ({extra})")
else:
_tlog(f"{self.label}: {dt_ms:.1f} ms")
# PARAMETERS
# Application constants
APP_VERSION = config.APP_VERSION
APP_FOLDER = config.APP_FOLDER
# Names
ORIGIN_THERMAL_IMAGES_NAME = config.ORIGIN_THERMAL_IMAGES_NAME
RGB_ORIGINAL_NAME = config.RGB_ORIGINAL_NAME
RGB_CROPPED_NAME = config.RGB_CROPPED_NAME
ORIGIN_TH_FOLDER = config.ORIGIN_TH_FOLDER
RGB_CROPPED_FOLDER = config.RGB_CROPPED_FOLDER
PROC_TH_FOLDER = config.PROC_TH_FOLDER
CUSTOM_IMAGES_FOLDER = config.CUSTOM_IMAGES_FOLDER
RECT_MEAS_NAME = config.RECT_MEAS_NAME
POINT_MEAS_NAME = config.POINT_MEAS_NAME
LINE_MEAS_NAME = config.LINE_MEAS_NAME
VIEWS = config.VIEWS
LEGEND = config.LEGEND
EDGE_COLOR = thermal_config.EDGE_COLOR
EDGE_BLUR_SIZE = thermal_config.EDGE_BLUR_SIZE
EDGE_METHOD = thermal_config.EDGE_METHOD
EDGE_OPACITY = thermal_config.EDGE_OPACITY
N_COLORS = thermal_config.N_COLORS
# FUNCTIONS
def get_next_available_folder(base_folder, app_folder_base_name=APP_FOLDER):
# Start with the initial folder name (i.e., 'IRLab_1')
folder_number = 1
while True:
# Construct the folder name with the current number
app_folder = os.path.join(base_folder, f"{app_folder_base_name}{folder_number}")
# Check if the folder already exists
if not os.path.exists(app_folder):
# If it doesn't exist, return the folder name
return app_folder
# Increment the folder number and try again
folder_number += 1
def add_item_in_tree(parent, line):
item = QStandardItem(line)
parent.appendRow(item)
def add_icon(img_source, pushButton_object):
"""
Function to add an icon to a pushButton
"""
pushButton_object.setIcon(QIcon(img_source))
# CLASSES
class SplashScreen(QSplashScreen):
"""A splash screen displayed during application startup."""
def __init__(self) -> None:
"""Initialize the splash screen with the application splash image."""
try:
splash_path = res.find('img/splash_thermogram.png')
if not os.path.exists(splash_path):
error("Splash image not found")
raise FileOperationError(f"Splash image not found at: {splash_path}")
pixmap = QPixmap(splash_path)
# Create splash screen first (super init)
super().__init__(pixmap)
# Now safe to access device pixel ratio
dpr = self.devicePixelRatioF()
self.setFixedSize(pixmap.size() / dpr) # Scale the window size appropriately
self.setWindowFlag(Qt.WindowType.FramelessWindowHint)
debug("Splash screen initialized successfully")
except Exception as e:
error(f"Failed to initialize splash screen: {str(e)}")
raise ThermogramError("Could not create splash screen") from e
class DroneIrWindow(QMainWindow):
"""Main application window for the IR Lab application.
Handles the primary user interface and functionality for thermal image processing,
including image loading, visualization, measurements, and analysis tools.
Attributes:
...
"""
def __init__(self, parent=None):
"""Initialize the main window and set up the user interface.
Args:
parent: Optional parent widget
Raises:
ThermogramError: If initialization fails
FileOperationError: If required UI files are not found
"""
super(DroneIrWindow, self).__init__(parent)
# Load the UI file
ui_file = Path(config.UI_DIR) / 'main_window.ui'
if not ui_file.exists():
error(f"UI file not found: {ui_file}")
raise FileOperationError(f"UI file not found: {ui_file}")
info(f"Loading UI file: {ui_file}")
uic.loadUi(str(ui_file), self)
# Boolean flag to track the stylesheet state
self.style_active = False
# Initialize status
self.update_progress(nb=100, text="Status: Choose image folder")
# Set up thread pool for background tasks
self.__pool = QThreadPool()
self.__pool.setMaxThreadCount(3)
debug(f"Thread pool initialized with {self.__pool.maxThreadCount()} threads")
# Initialize core components
self.initialize_variables()
self.initialize_tree_view()
# Edge detection settings
self.edges = False
self.edge_color = EDGE_COLOR
self.edge_blur = False
self.edge_bil = True
self.edge_blur_size = EDGE_BLUR_SIZE
self.edge_method = EDGE_METHOD
self.edge_opacity = EDGE_OPACITY
# Other options
self.skip_update = False
# Initialize combo box content
self._setup_combo_boxes()
# Set up UI components
self._setup_ui_components()
# create connections (signals)
self.create_connections()
# Add icons to buttons
self.add_all_icons()
if hasattr(self, "actionFlight_map"):
self.actionFlight_map.setEnabled(False)
# BASIC SETUP _________________________________________________________________
def _setup_combo_boxes(self) -> None:
"""Initialize and populate combo boxes with their respective items."""
try:
# Initialize color limit options
self._out_of_lim = tt.OUT_LIM
self._out_of_matp = tt.OUT_LIM_MATPLOT
self._img_post = tt.POST_PROCESS
self._colormap_list = tt.COLORMAPS
self._view_list = copy.deepcopy(VIEWS)
# Set up legend combobox
self.comboBox_legend_type.clear()
self.comboBox_legend_type.addItems(LEGEND)
# Set up colormap combobox
self.comboBox_palette.clear()
self.comboBox_palette.addItems(tt.COLORMAP_NAMES)
self.comboBox_palette.setCurrentIndex(0)
# Set up edge style combobox
self.comboBox_edge_overlay_selection.clear()
self.comboBox_edge_overlay_selection.addItems(tt.EDGE_STYLE_NAMES)
self.comboBox_edge_overlay_selection.setCurrentIndex(0)
# Set up color limit combo boxes
self.comboBox_colors_low.clear()
self.comboBox_colors_low.addItems(self._out_of_lim)
self.comboBox_colors_low.setCurrentIndex(0)
self.comboBox_colors_high.clear()
self.comboBox_colors_high.addItems(self._out_of_lim)
self.comboBox_colors_high.setCurrentIndex(0)
self.comboBox_view.addItems(self._view_list)
self.comboBox_post.addItems(self._img_post)
debug("Combo boxes initialized successfully")
except Exception as e:
error(f"Failed to initialize combo boxes: {str(e)}")
raise ThermogramError("Failed to initialize combo boxes") from e
def _setup_ui_components(self) -> None:
"""Initialize and set up UI components."""
try:
# Group dock widgets
self.tabifyDockWidget(self.dockWidget, self.dockWidget_2)
self.dockWidget.raise_() # Make the first dock widget visible by default
self._rearrange_docks()
# Set up range slider
self.range_slider = wid.QRangeSlider(tt.COLORMAPS[0])
self.range_slider.setEnabled(False)
self.range_slider.setLowerValue(0)
self.range_slider.setUpperValue(20)
self.range_slider.setMinimum(0)
self.range_slider.setMaximum(20)
self.range_slider.setFixedHeight(45)
# Add range slider to layout
self.horizontalLayout_slider.addWidget(self.range_slider)
# Sliders options
self.slider_sensitive = True
# Create validator for qlineedit
onlyInt = QIntValidator()
onlyInt.setRange(0, 999)
self.lineEdit_colors.setValidator(onlyInt)
self.n_colors = N_COLORS # default number of colors
self.lineEdit_colors.setText(str(N_COLORS))
# Add actions to action group (mutually exclusive functions)
ag = QActionGroup(self)
ag.setExclusive(True)
ag.addAction(self.actionRectangle_meas)
ag.addAction(self.actionHand_selector)
ag.addAction(self.actionSpot_meas)
ag.addAction(self.actionLine_meas)
# Set up photo viewers
self.viewer = wid.PhotoViewer(self)
self.verticalLayout_8.addWidget(self.viewer)
self.dual_viewer = wid.DualViewer()
self.verticalLayout_10.addWidget(self.dual_viewer)
except Exception as e:
error(f"Failed to initialize UI components: {str(e)}")
raise ThermogramError("Failed to initialize UI components") from e
def _rearrange_docks(self) -> None:
"""Adjust dock placement to reduce left-panel crowding."""
# Move Edge mix dock to the right pane
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dockWidget_edge)
# Move legend controls from Options dock to Temperatures dock
temp_layout = getattr(self, 'verticalLayout_2', None)
legend_widgets = [
getattr(self, 'checkBox_legend', None),
getattr(self, 'label_12', None),
getattr(self, 'comboBox_legend_type', None),
]
if temp_layout is not None:
insert_pos = temp_layout.count()
for i in range(temp_layout.count()):
item = temp_layout.itemAt(i)
if item is not None and item.spacerItem() is not None:
insert_pos = i
break
for widget in legend_widgets:
if widget is None:
continue
temp_layout.insertWidget(insert_pos, widget)
insert_pos += 1
# Options dock is now empty; remove it from docking layout
if hasattr(self, 'dockWidget_4'):
self.removeDockWidget(self.dockWidget_4)
self.dockWidget_4.hide()
def initialize_variables(self):
"""Initialize instance variables with default values.
Sets up various flags and variables used throughout the application for
tracking state, image properties, and user settings.
"""
try:
# Set bool variables
self.has_rgb = True # does the dataset have RGB image
self.rgb_shown = False
self.save_colormap_info = True # TODO make use of it... if True, the colormap and temperature options will be stored for each picture
# Set path variables
self.custom_images = []
self.list_rgb_paths = []
self.list_ir_paths = []
self.list_z_paths = []
self.ir_folder = ''
self.rgb_folder = ''
self.preview_folder = ''
# Set other variables
self.colormap = None
self.number_custom_pic = 0
# Image lists
self.ir_imgs = ''
self.rgb_imgs = ''
self.n_imgs = len(self.ir_imgs)
self.nb_sets = 0
# Cache for generated preview files (thermal render) to speed up switching
self._preview_cache_files = []
# list images classes (where to store all measurements and annotations)
self.images = []
self.work_image = None
# histogram
self.hist_canvas = None
self.current_view = 0
# Temperature display unit ('C' or 'F')
self.temp_unit = 'C'
# Default thermal options:
self.thermal_param = {'emissivity': thermal_config.DEFAULT_EMISSIVITY,
'distance': thermal_config.DEFAULT_DISTANCE,
'humidity': thermal_config.DEFAULT_HUMIDITY,
'reflection': thermal_config.DEFAULT_REFLECTION}
self.lineEdit_emissivity.setText(str(round(self.thermal_param['emissivity'], 2)))
self.lineEdit_distance.setText(str(round(self.thermal_param['distance'], 2)))
self.lineEdit_refl_temp.setText(str(round(self.thermal_param['reflection'], 2)))
# Image iterator to know which image is active
self.active_image = 0
debug("Variables initialized successfully")
except Exception as e:
error(f"Failed to initialize variables: {str(e)}")
raise ThermogramError(f"Failed to initialize application: {str(e)}") from e
def store_variables(self):
pass
def initialize_tree_view(self):
"""Initialize the tree view for displaying image measurements and annotations.
Sets up the tree view model and configures its appearance and behavior.
The tree view is used to display hierarchical data about measurements
and annotations made on the thermal images.
"""
try:
# Create model (for the tree structure)
self.model = QStandardItemModel()
self.treeView.setModel(self.model)
self.treeView.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.treeView.customContextMenuRequested.connect(self.onContextMenu)
# Add measurement and annotations categories to tree view
add_item_in_tree(self.model, RECT_MEAS_NAME)
add_item_in_tree(self.model, POINT_MEAS_NAME)
add_item_in_tree(self.model, LINE_MEAS_NAME)
self.model.setHeaderData(0, Qt.Orientation.Horizontal, 'Added Data')
except Exception as e:
error(f"Failed to initialize tree view: {str(e)}")
raise ThermogramError("Failed to initialize tree view") from e
def create_connections(self):
"""Create signal-slot connections for UI elements.
Connects various UI elements (buttons, menus, etc.) to their corresponding
handler methods. This sets up the interactive behavior of the application.
"""
try:
# IO actions
self.actionLoad_folder.triggered.connect(self.load_folder_phase1)
self.actionReset_all.triggered.connect(self.full_reset)
self.actionToggle_stylesheet.triggered.connect(self.toggle_stylesheet)
self.actionOptions.triggered.connect(self.open_options)
self.actionGlobal_refl_adjust.triggered.connect(self.global_adjust_refl_temp)
# Processing actions
self.actionRectangle_meas.triggered.connect(self.rectangle_meas)
self.actionSpot_meas.triggered.connect(self.point_meas)
self.actionLine_meas.triggered.connect(self.line_meas)
self.action3D_temperature.triggered.connect(self.show_viz_threed)
self.actionFind_maxima.triggered.connect(self.find_maxima)
self.actionDetect_object.triggered.connect(self.detect_object)
self.actionCompose.triggered.connect(self.compose_pic)
# Export action
self.actionSave_Image.triggered.connect(self.save_image)
self.actionProcess_all.triggered.connect(self.batch_export)
self.actionCreate_anim.triggered.connect(self.export_anim)
self.actionCreate_Report.triggered.connect(self.create_report)
if hasattr(self, "actionFlight_map"):
self.actionFlight_map.triggered.connect(self.show_flight_map)
# Other actions
self.actionInfo.triggered.connect(self.show_info)
self.actionRadiometric_parameters.triggered.connect(self.show_radio_dock)
self.actionEdge_Mix.triggered.connect(self.show_edge_dock)
# Viewers
self.viewer.endDrawing_rect_meas.connect(self.add_rect_meas)
self.viewer.endDrawing_point_meas.connect(self.add_point_meas)
self.viewer.endDrawing_line_meas.connect(self.add_line_meas)
# PushButtons
self.pushButton_left.clicked.connect(lambda: self.update_img_to_preview('minus'))
self.pushButton_right.clicked.connect(lambda: self.update_img_to_preview('plus'))
self.pushButton_estimate.clicked.connect(self.estimate_temp)
self.pushButton_adjust_refl_temp.clicked.connect(self.adjust_refl_temp_from_previous)
self.pushButton_meas_color.clicked.connect(self.change_meas_color)
self.pushButton_match.clicked.connect(self.image_matching)
self.pushButton_edge_options.clicked.connect(self.edge_options)
self.pushButton_delete_points.clicked.connect(lambda: self.remove_annotations('point'))
self.pushButton_delete_lines.clicked.connect(lambda: self.remove_annotations('line'))
self.pushButton_delete_area.clicked.connect(lambda: self.remove_annotations('area'))
self.pushButton_reset_range.clicked.connect(self.reset_temp_range)
self.pushButton_heatflow.clicked.connect(self.viz_heatflow)
self.pushButton_optimhisto.clicked.connect(self.optimal_range)
self.pushButton_apply_temp_all.clicked.connect(self.apply_temp_settings_to_all)
self.pushButton_apply_palette_all.clicked.connect(self.apply_palette_settings_to_all)
self.pushButton_apply_radio_all.clicked.connect(self.apply_radiometric_settings_to_all)
self.pushButton_add_custom_palette.clicked.connect(self.add_palette)
# Dropdowns Comboboxes
self.comboBox_palette.currentIndexChanged.connect(self.update_img_preview)
self.comboBox_colors_low.currentIndexChanged.connect(self.update_img_preview)
self.comboBox_colors_high.currentIndexChanged.connect(self.update_img_preview)
self.comboBox_post.currentIndexChanged.connect(self.update_img_preview)
self.comboBox_img.currentIndexChanged.connect(lambda: self.update_img_to_preview('other'))
self.comboBox_view.currentIndexChanged.connect(self.update_img_preview)
self.comboBox_edge_overlay_selection.currentIndexChanged.connect(self.change_edge_style)
self.comboBox_legend_type.currentIndexChanged.connect(self.update_img_preview)
# Line edits
self.lineEdit_min_temp.editingFinished.connect(self.adapt_slider_values)
self.lineEdit_max_temp.editingFinished.connect(self.adapt_slider_values)
self.lineEdit_colors.editingFinished.connect(self.update_img_preview)
self.lineEdit_emissivity.editingFinished.connect(self.define_thermal_parameters)
self.lineEdit_distance.editingFinished.connect(self.define_thermal_parameters)
self.lineEdit_refl_temp.editingFinished.connect(self.define_thermal_parameters)
# Double slider
self.range_slider.lowerValueChanged.connect(self.change_line_edits)
self.range_slider.upperValueChanged.connect(self.change_line_edits)
# Checkboxes
self.checkBox_legend.stateChanged.connect(self.toggle_legend)
self.checkBox_edges.stateChanged.connect(self.activate_edges)
if hasattr(self, 'checkBox_report'):
self.checkBox_report.stateChanged.connect(self.toggle_report_inclusion)
# Remarks text edit
if hasattr(self, 'plainTextEdit_remarks'):
self.plainTextEdit_remarks.textChanged.connect(self.save_remarks)
# tab widget
self.tabWidget.currentChanged.connect(self.on_tab_change)
except Exception as e:
error(f"Failed to create UI connections: {str(e)}")
raise ThermogramError("Failed to create UI connections") from e
# THERMAL PARAMETERS FUNCTIONS __________________________________________________________________________
def define_thermal_parameters(self):
try:
# Store original values to restore if validation fails
original_thermal_param = copy.deepcopy(self.thermal_param)
em = float(self.lineEdit_emissivity.text())
# check if value is acceptable
if em < 0.1 or em > 1:
self.lineEdit_emissivity.setText(str(round(self.thermal_param['emissivity'], 2)))
raise ValueError
else:
self.thermal_param['emissivity'] = em
dist = float(self.lineEdit_distance.text())
if dist < 1 or dist > 25:
self.lineEdit_distance.setText(str(round(self.thermal_param['distance'], 1)))
raise ValueError
else:
self.thermal_param['distance'] = dist
refl_temp = float(self.lineEdit_refl_temp.text())
if refl_temp < -40 or refl_temp > 500:
self.lineEdit_refl_temp.setText(str(round(self.thermal_param['reflection'], 1)))
raise ValueError
else:
self.thermal_param['reflection'] = refl_temp
# Apply the new radiometric parameters directly to the current image
self.work_image.update_data_from_param(copy.deepcopy(self.thermal_param))
# Update slider and line edits with the new temperature range
tmin, tmax, tmin_shown, tmax_shown = self.work_image.get_temp_data()
self.slider_sensitive = False
self.lineEdit_min_temp.setText(str(round(self.display_temp(tmin_shown), 2)))
self.lineEdit_max_temp.setText(str(round(self.display_temp(tmax_shown), 2)))
self.range_slider.setMinimum(int(self.display_temp(tmin) * 100))
self.range_slider.setMaximum(int(self.display_temp(tmax) * 100))
self.range_slider.setLowerValue(self.display_temp(tmin_shown) * 100)
self.range_slider.setUpperValue(self.display_temp(tmax_shown) * 100)
self.slider_sensitive = True
self.retrace_items()
self.update_img_preview()
except ValueError:
QMessageBox.warning(self, "Warning",
"Oops! Some of the values are not valid!")
self.thermal_param = original_thermal_param
# TEMPERATURE RANGE _________________________________________________________________
def adapt_slider_values(self):
"""Update temperature range based on slider values.
Updates the temperature range display and image visualization based on
the current values of the LineEdits. Includes validation to ensure
values stay within valid bounds.
"""
# Temporarily disable slider sensitivity to avoid feedback loops
try:
# Temporarily disable slider sensitivity to avoid loops
self.slider_sensitive = False
# Get current temperature values from Linedits (in display units)
tmin_display = float(self.lineEdit_min_temp.text())
tmax_display = float(self.lineEdit_max_temp.text())
# Check boundaries validity
if not self.skip_update:
if tmax_display <= tmin_display:
QMessageBox.warning(self, "Warning",
"Oops! A least one of the temperatures is not valid. Try again...")
self.lineEdit_min_temp.setText(str(round(self.display_temp(self.work_image.tmin_shown), 2)))
self.lineEdit_max_temp.setText(str(round(self.display_temp(self.work_image.tmax_shown), 2)))
return
# Expand slider min/max so handles stay visible even if user types
# temperatures outside the image's natural range
new_min = int(min(tmin_display * 100, self.range_slider.minimum()))
new_max = int(max(tmax_display * 100, self.range_slider.maximum()))
self.range_slider.setMinimum(new_min)
self.range_slider.setMaximum(new_max)
# Adapt sliders (slider works in display units * 100)
self.range_slider.setLowerValue(tmin_display * 100)
self.range_slider.setUpperValue(tmax_display * 100)
debug(f"Temperature range updated: {tmin_display:.1f} - {tmax_display:.1f} {self.temp_unit_suffix()}")
except Exception as e:
error(f"Error updating temperature range: {str(e)}")
self.lineEdit_min_temp.setText(str(round(self.display_temp(self.work_image.tmin_shown), 2)))
self.lineEdit_max_temp.setText(str(round(self.display_temp(self.work_image.tmax_shown), 2)))
finally:
# Re-enable slider sensitivity
self.slider_sensitive = True
self.update_img_preview()
def change_line_edits(self, value):
if self.slider_sensitive:
tmin = self.range_slider.lowerValue() / 100.0 # Adjust if you used scaling
tmax = self.range_slider.upperValue() / 100.0
self.lineEdit_min_temp.setText(str(round(tmin, 2)))
self.lineEdit_max_temp.setText(str(round(tmax, 2)))
self.update_img_preview()
def optimal_range(self):
self.slider_sensitive = False
tmin_shown, tmax_shown = self.work_image.compute_optimal_temp_range()
tmin_d = self.display_temp(tmin_shown)
tmax_d = self.display_temp(tmax_shown)
self.lineEdit_min_temp.setText(str(round(tmin_d, 2)))
self.lineEdit_max_temp.setText(str(round(tmax_d, 2)))
# Expand slider min/max so handles stay visible
new_min = int(min(tmin_d * 100, self.range_slider.minimum()))
new_max = int(max(tmax_d * 100, self.range_slider.maximum()))
self.range_slider.setMinimum(new_min)
self.range_slider.setMaximum(new_max)
self.range_slider.setLowerValue(tmin_d * 100)
self.range_slider.setUpperValue(tmax_d * 100)
self.slider_sensitive = True
self.update_img_preview()
def reset_temp_range(self):
"""Reset the temperature range to the full range of the current image.
Updates the temperature range slider and display to show the full
temperature range of the current thermal image. This resets any user-defined
temperature range limits.
"""
try:
self.slider_sensitive = False
self.work_image.update_data_from_param(copy.deepcopy(self.work_image.thermal_param))
tmin, tmax, _, _ = self.work_image.get_temp_data()
# Fill values lineedits (in display units)
tmin_d = self.display_temp(tmin)
tmax_d = self.display_temp(tmax)
self.lineEdit_min_temp.setText(str(round(tmin_d, 2)))
self.lineEdit_max_temp.setText(str(round(tmax_d, 2)))
# Set min/max before handle values so handles are always within range
self.range_slider.setMinimum(int(tmin_d * 100))
self.range_slider.setMaximum(int(tmax_d * 100))
self.range_slider.setLowerValue(tmin_d * 100)
self.range_slider.setUpperValue(tmax_d * 100)
debug(f"Temperature range reset to {tmin_d:.1f} - {tmax_d:.1f} {self.temp_unit_suffix()}")
except Exception as e:
error(f"Failed to reset temperature range: {str(e)}")
raise ThermogramError("Failed to reset temperature range") from e
finally:
self.slider_sensitive = True
self.update_img_preview()
def estimate_temp(self):
ref_pic_name = QFileDialog.getOpenFileName(self, 'Open file',
self.ir_folder, "Image files (*.jpg *.JPG *.gif)")
img_path = ref_pic_name[0]
if img_path != '':
tmin, tmax = tt.compute_delta(img_path, self.thermal_param)
self.lineEdit_min_temp.setText(str(round(self.display_temp(tmin), 2)))
self.lineEdit_max_temp.setText(str(round(self.display_temp(tmax), 2)))
self.update_img_preview()
def adjust_refl_temp_from_previous(self):
"""Adjust the reflective temperature of the current image so that its
temperature distribution matches the previous image's distribution."""
if self.active_image == 0:
QMessageBox.warning(self, "Warning",
"There is no previous image to match against.")
return
try:
QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
# Get the previous image and ensure its data is loaded
prev_image = self.images[self.active_image - 1]
prev_image.ensure_data_loaded(reset_shown_values=False)
ref_raw_data = prev_image.raw_data_undis
# Run the optimisation
optimal_refl = self.work_image.find_matching_refl_temp(ref_raw_data)
# Apply the new reflective temperature
self.thermal_param['reflection'] = optimal_refl
self.work_image.update_data_from_param(copy.deepcopy(self.thermal_param))
# Update UI
self.lineEdit_refl_temp.setText(str(round(optimal_refl, 2)))
tmin, tmax, tmin_shown, tmax_shown = self.work_image.get_temp_data()
self.slider_sensitive = False
self.lineEdit_min_temp.setText(str(round(self.display_temp(tmin_shown), 2)))
self.lineEdit_max_temp.setText(str(round(self.display_temp(tmax_shown), 2)))
self.range_slider.setMinimum(int(self.display_temp(tmin) * 100))
self.range_slider.setMaximum(int(self.display_temp(tmax) * 100))
self.range_slider.setLowerValue(self.display_temp(tmin_shown) * 100)
self.range_slider.setUpperValue(self.display_temp(tmax_shown) * 100)
self.slider_sensitive = True
self.retrace_items()
self.update_img_preview()
debug(f"Reflective temperature adjusted to {optimal_refl:.2f} °C "
f"(matching image {self.active_image - 1})")
except Exception as e:
error(f"Failed to adjust reflective temperature: {str(e)}")
QMessageBox.warning(self, "Error",
f"Failed to adjust reflective temperature:\n{str(e)}")
finally:
QApplication.restoreOverrideCursor()
def global_adjust_refl_temp(self):
"""Sequentially adjust the reflective temperature of every image so that
each image's temperature distribution matches the previous one.
Image 1 is kept as-is. Image 2 is tuned to match image 1, image 3 to
match image 2, and so on.
"""
n = len(self.images)
if n < 2:
QMessageBox.warning(self, "Warning",
"At least two images are required for global adjustment.")
return
reply = QMessageBox.question(
self, "Global Refl. Temp. Adjustment",
f"This will sequentially adjust the reflected temperature for "
f"{n - 1} image(s), using each previous image as reference.\n\n"
f"Proceed?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.Yes)
if reply != QMessageBox.StandardButton.Yes:
return
try:
QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
# Make sure image 0 has its data loaded
self.images[0].ensure_data_loaded(reset_shown_values=False)
adjusted = []
for i in range(1, n):
prev_img = self.images[i - 1]
cur_img = self.images[i]
# Ensure both images have data
prev_img.ensure_data_loaded(reset_shown_values=False)
cur_img.ensure_data_loaded(reset_shown_values=False)
ref_raw_data = prev_img.raw_data_undis
# Find optimal reflective temperature
optimal_refl = cur_img.find_matching_refl_temp(ref_raw_data)
# Apply it
new_param = dict(cur_img.thermal_param)
new_param['reflection'] = optimal_refl
cur_img.update_data_from_param(new_param)
adjusted.append((i, optimal_refl))
debug(f"Global refl. adjust: image {i} -> refl={optimal_refl:.2f} °C")
# Refresh the currently displayed image
self.work_image = self.images[self.active_image]
self.thermal_param = copy.deepcopy(self.work_image.thermal_param)
self.lineEdit_refl_temp.setText(str(round(self.thermal_param['reflection'], 2)))
tmin, tmax, tmin_shown, tmax_shown = self.work_image.get_temp_data()
self.slider_sensitive = False
self.lineEdit_min_temp.setText(str(round(self.display_temp(tmin_shown), 2)))
self.lineEdit_max_temp.setText(str(round(self.display_temp(tmax_shown), 2)))
self.range_slider.setMinimum(int(self.display_temp(tmin) * 100))
self.range_slider.setMaximum(int(self.display_temp(tmax) * 100))
self.range_slider.setLowerValue(self.display_temp(tmin_shown) * 100)
self.range_slider.setUpperValue(self.display_temp(tmax_shown) * 100)
self.slider_sensitive = True
self.retrace_items()
self.update_img_preview()
summary = "\n".join(f" Image {idx}: {refl:.2f} °C" for idx, refl in adjusted)
info(f"Global refl. temp. adjustment complete:\n{summary}")
QMessageBox.information(
self, "Done",
f"Reflected temperature adjusted for {len(adjusted)} image(s).\n\n{summary}")
except Exception as e:
error(f"Global refl. temp. adjustment failed: {str(e)}")
QMessageBox.warning(self, "Error",
f"Global adjustment failed:\n{str(e)}")
finally:
QApplication.restoreOverrideCursor()
def apply_temp_settings_to_all(self):
"""Apply the current image's temperature display settings to all loaded images."""
try:
tmin_display = float(self.lineEdit_min_temp.text())
tmax_display = float(self.lineEdit_max_temp.text())
# Convert from display unit back to Celsius for internal storage
tmin_c = self.to_celsius(tmin_display)
tmax_c = self.to_celsius(tmax_display)
for img in self.images:
img.tmin_shown = tmin_c
img.tmax_shown = tmax_c
info(f"Applied temperature settings ({tmin_display:.2f} - {tmax_display:.2f} {self.temp_unit_suffix()}) to all {len(self.images)} images")
QMessageBox.information(self, "Done",
f"Temperature range ({tmin_display:.2f} – {tmax_display:.2f} {self.temp_unit_suffix()}) "
f"applied to all {len(self.images)} images.")
except Exception as e:
error(f"Failed to apply temperature settings to all: {str(e)}")
QMessageBox.warning(self, "Error",
f"Failed to apply temperature settings:\n{str(e)}")
def apply_palette_settings_to_all(self):
"""Apply the current image's palette/colormap settings to all loaded images."""
try:
self.compile_user_values()
colormap = self.work_image.colormap
n_colors = self.work_image.n_colors
col_high = self.work_image.user_lim_col_high
col_low = self.work_image.user_lim_col_low
post_process = self.work_image.post_process
for img in self.images:
img.colormap = colormap
img.n_colors = n_colors
img.user_lim_col_high = col_high
img.user_lim_col_low = col_low
img.post_process = post_process
info(f"Applied palette settings (colormap={colormap}) to all {len(self.images)} images")
QMessageBox.information(self, "Done",
f"Palette settings (colormap: {colormap}) "
f"applied to all {len(self.images)} images.")
except Exception as e:
error(f"Failed to apply palette settings to all: {str(e)}")
QMessageBox.warning(self, "Error",
f"Failed to apply palette settings:\n{str(e)}")
def apply_radiometric_settings_to_all(self):
"""Apply the current radiometric parameters to all loaded images."""
try:
QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
params = copy.deepcopy(self.thermal_param)
for img in self.images:
img.update_data_from_param(copy.deepcopy(params))
info(f"Applied radiometric settings to all {len(self.images)} images: {params}")
QMessageBox.information(self, "Done",
f"Radiometric settings (emissivity={params['emissivity']}, "
f"distance={params['distance']}, "
f"reflection={params['reflection']}) "
f"applied to all {len(self.images)} images.")
except Exception as e:
error(f"Failed to apply radiometric settings to all: {str(e)}")
QMessageBox.warning(self, "Error",
f"Failed to apply radiometric settings:\n{str(e)}")
finally:
QApplication.restoreOverrideCursor()
# PALETTE _________________________________________________________________
def add_palette(self):
"""
Opens a dialog to create a custom color palette and adds it to the available palettes.
The user can define color steps and preview the palette before saving it.
"""
from dialogs import CustomPaletteDialog
import matplotlib.colors as mcol
import numpy as np
# Create and show the custom palette dialog
dialog = CustomPaletteDialog(self)
if dialog.exec():
# Get the palette data from the dialog
palette_data = dialog.get_palette_data()
if not palette_data:
self.statusbar.showMessage("Invalid palette data", 3000)
return
palette_name = palette_data['name']
colors = palette_data['colors']
# Check if the name already exists
if palette_name in tt.LIST_CUSTOM_NAMES or palette_name in tt.COLORMAP_NAMES:
# Add a suffix to make it unique
i = 1
original_name = palette_name
while palette_name in tt.LIST_CUSTOM_NAMES or palette_name in tt.COLORMAP_NAMES:
palette_name = f"{original_name}_{i}"
i += 1
info(f"Renamed palette to '{palette_name}' to avoid name collision")
# Add the new palette to the global lists
tt.LIST_CUSTOM_NAMES.append(palette_name)
tt.COLORMAP_NAMES.append(palette_name)
tt.COLORMAPS.append(palette_name)
# Create and register the new colormap
tt.register_custom_cmap(palette_name, colors)
# Update the combobox with the new palette
current_index = self.comboBox_palette.currentIndex()
self.comboBox_palette.clear()
self.comboBox_palette.addItems(tt.COLORMAP_NAMES)
# Find the index of the new palette and select it
new_index = tt.COLORMAP_NAMES.index(palette_name)
self.comboBox_palette.setCurrentIndex(new_index)
# Show success message
self.statusbar.showMessage(f"Custom palette '{palette_name}' created successfully", 3000)
info(f"Created custom palette: {palette_name}")
# ANNOTATIONS _________________________________________________________________
def viz_heatflow(self):
tt.create_vector_plot(self.work_image)
def add_rect_meas(self, rect_item):
"""
Add a region of interest coming from the rectangle tool
:param rect_item: a rectangle item from the viewer
"""
# create annotation (object)
new_rect_annot = tt.RectMeas(rect_item)
# get image data
if self.has_rgb:
rgb_path = os.path.join(self.rgb_folder, self.rgb_imgs[self.active_image])
else:
rgb_path = ''
new_rect_annot.has_rgb = False
ir_path = self.dest_path_post
coords = new_rect_annot.get_coord_from_item(rect_item)
roi_ir, roi_rgb = new_rect_annot.compute_data(coords, self.work_image.raw_data_undis, rgb_path, ir_path)
roi_ir_path = os.path.join(self.preview_folder, 'roi_ir.JPG')
tt.cv_write_all_path(roi_ir, roi_ir_path)
if self.has_rgb:
roi_rgb_path = os.path.join(self.preview_folder, 'roi_rgb.JPG')
tt.cv_write_all_path(roi_rgb, roi_rgb_path)
else:
roi_rgb_path = ''
# add interesting data to viewer
new_rect_annot.compute_highlights(temp_unit=self.temp_unit)
new_rect_annot.create_items(temp_unit=self.temp_unit)
for item in new_rect_annot.ellipse_items:
self.viewer.add_item_from_annot(item)
for item in new_rect_annot.text_items: