-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1758 lines (1407 loc) · 69.3 KB
/
main.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
"""
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: sdu@bbri.be
TODO:
- Allow to import only thermal pictures - OK
- Implement 'context' dialog --> Drone info + location
- Allow the user to define a custom folder - OK
- 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
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 utils.config import config, thermal_config
from utils.logger import info, error, debug, warning
from utils.exceptions import ThermogramError, FileOperationError
# 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
RECT_MEAS_NAME = config.RECT_MEAS_NAME
POINT_MEAS_NAME = config.POINT_MEAS_NAME
LINE_MEAS_NAME = config.LINE_MEAS_NAME
EDGE_COLOR = 'white'
EDGE_BLUR_SIZE = 3
EDGE_METHOD = 0
EDGE_OPACITY = 0.7
VIEWS = config.VIEWS
def get_next_available_folder(base_folder, app_folder_base_name=APP_FOLDER):
# Start with the initial folder name (i.e., 'ThermogramApp_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
# CLASSES
class SplashScreen(QSplashScreen):
"""A splash screen displayed during application startup.
Displays a splash image while the main application is loading.
"""
def __init__(self) -> None:
"""Initialize the splash screen with the application splash image."""
try:
splash_path = res.find('img/splash.png')
if not os.path.exists(splash_path):
error("Splash image not found")
raise FileOperationError(f"Splash image not found at: {splash_path}")
super().__init__(QPixmap(splash_path))
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 Thermogram 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 = True
# 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()
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 = VIEWS
# Add content to comboboxes
self.comboBox.clear()
self.comboBox.addItems(tt.COLORMAP_NAMES)
self.comboBox.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
# 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 = 256 # default number of colors
self.lineEdit_colors.setText(str(256))
# 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 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
# list images classes (where to store all measurements and annotations)
self.images = []
self.work_image = None
# 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}
# 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 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
self.add_item_in_tree(self.model, RECT_MEAS_NAME)
self.add_item_in_tree(self.model, POINT_MEAS_NAME)
self.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)
# 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)
# 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_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)
# Dropdowns
self.comboBox.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)
# Line edits
self.lineEdit_min_temp.editingFinished.connect(self.change_slider_values)
self.lineEdit_max_temp.editingFinished.connect(self.change_slider_values)
self.lineEdit_colors.editingFinished.connect(self.update_img_preview)
self.lineEdit_emissivity.editingFinished.connect(self.define_options)
self.lineEdit_distance.editingFinished.connect(self.define_options)
self.lineEdit_refl_temp.editingFinished.connect(self.define_options)
# 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)
# 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
def show_radio_dock(self):
"""
Show the radiometric parameters dock widget if it's hidden or closed.
"""
if not self.dockWidget_radio.isVisible():
self.dockWidget_radio.show()
def show_edge_dock(self):
"""
Show the edge mix dock widget if it's hidden or closed.
"""
if not self.dockWidget_edge.isVisible():
self.dockWidget_edge.show()
def on_tab_change(self, index):
"""Handle tab widget changes.
Enables or disables certain UI elements based on the selected tab.
Args:
index: Index of the newly selected tab
"""
if index == 1:
self.actionRectangle_meas.setDisabled(True)
self.actionSpot_meas.setDisabled(True)
self.actionLine_meas.setDisabled(True)
else:
self.actionRectangle_meas.setDisabled(False)
self.actionSpot_meas.setDisabled(False)
self.actionLine_meas.setDisabled(False)
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.work_image.update_data(copy.deepcopy(self.work_image.thermal_param))
self.tmin, self.tmax, self.tmin_shown, self.tmax_shown = self.work_image.get_temp_data()
# Fill values lineedits
self.lineEdit_min_temp.setText(str(round(self.tmin_shown, 2)))
self.lineEdit_max_temp.setText(str(round(self.tmax_shown, 2)))
self.range_slider.setLowerValue(self.tmin_shown * 100)
self.range_slider.setUpperValue(self.tmax_shown * 100)
self.range_slider.setMinimum(int(self.tmin * 100))
self.range_slider.setMaximum(int(self.tmax * 100))
debug(f"Temperature range reset to {self.tmin_shown:.1f} - {self.tmax_shown:.1f}")
except Exception as e:
error(f"Failed to reset temperature range: {str(e)}")
raise ThermogramError("Failed to reset temperature range") from e
def change_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 feedback loops
self.slider_sensitive = False
# Get current temperature values from Linedits
tmin = float(self.lineEdit_min_temp.text())
tmax = float(self.lineEdit_max_temp.text())
# Check boundaries validity
if tmax <= tmin:
QMessageBox.warning(self, "Warning",
"Oops! A least one of the temperatures is not valid. Try again...")
self.lineEdit_min_temp.setText(str(round(self.work_image.tmin_shown, 2)))
self.lineEdit_max_temp.setText(str(round(self.work_image.tmax_shown, 2)))
return
# Validate against image temperature bounds
if self.work_image:
# Clamp minimum temperature
if tmin < self.work_image.tmin:
tmin = self.work_image.tmin
self.work_image.tmin_shown = tmin
debug(f"Clamped minimum temperature to {tmin}")
# Clamp maximum temperature
if tmax > self.work_image.tmax:
tmax = self.work_image.tmax
self.work_image.tmax_shown = tmax
debug(f"Clamped maximum temperature to {tmax}")
# Update display
self.work_image.tmin_shown = tmin
self.work_image.tmax_shown = tmax
# Update UI
self.lineEdit_min_temp.setText(f"{tmin:.1f}")
self.lineEdit_max_temp.setText(f"{tmax:.1f}")
# Refresh image with new temperature range
self.update_img_preview()
# Adapt sliders
self.range_slider.setLowerValue(tmin * 100)
self.range_slider.setUpperValue(tmax * 100)
debug(f"Temperature range updated: {tmin:.1f} - {tmax:.1f}")
except Exception as e:
error(f"Error updating temperature range: {str(e)}")
raise ThermogramError("Failed to update temperature range") from e
self.lineEdit_min_temp.setText(str(round(self.work_image.tmin_shown, 2)))
self.lineEdit_max_temp.setText(str(round(self.work_image.tmax_shown, 2)))
finally:
# Re-enable slider sensitivity
self.slider_sensitive = True
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 update_img_list(self):
"""Update the list of images and initialize image processing classes.
Updates the internal list of thermal and RGB images, and initializes
the necessary image processing classes for each image pair. This method
is called after loading a new folder of images.
Raises:
ThermogramError: If there's an error updating the image list
FileOperationError: If required image files are not found
"""
try:
self.ir_folder = self.original_th_img_folder
if self.has_rgb:
self.rgb_folder = self.rgb_crop_img_folder
rgb_imgs = os.listdir(self.rgb_folder)
self.rgb_imgs = sorted(rgb_imgs)
# list thermal images
ir_imgs = os.listdir(self.ir_folder)
self.ir_imgs = sorted(ir_imgs)
self.n_imgs = len(self.ir_imgs)
if self.n_imgs > 1:
self.pushButton_right.setEnabled(True)
# update progress
self.update_progress(nb=5, text='Creating image objects....')
# Create an image object for each picture
for i, im in enumerate(self.ir_imgs):
if self.n_imgs == 1:
progress = 100 # or any other value that makes sense in your context
else:
progress = 5 + (95 * i) / (self.n_imgs - 1)
self.update_progress(nb=progress, text=f'Creating image object {i}/{self.n_imgs}')
if self.has_rgb:
print('Has rgb!')
image = tt.ProcessedIm(os.path.join(self.ir_folder, im),
os.path.join(self.rgb_folder, self.rgb_imgs[i]),
self.list_rgb_paths[i], self.ir_undistorder, self.drone_model)
else:
image = tt.ProcessedIm(os.path.join(self.ir_folder, im), '', '', self.ir_undistorder,
self.drone_model)
self.images.append(image)
# Define active image
self.active_image = 0
self.work_image = self.images[self.active_image]
# Create temporary folder
self.preview_folder = os.path.join(self.ir_folder, 'preview')
if not os.path.exists(self.preview_folder):
os.mkdir(self.preview_folder)
# Quickly compute temperature delta on first image
self.tmin = copy.deepcopy(self.work_image.tmin)
self.tmax = copy.deepcopy(self.work_image.tmax)
self.lineEdit_min_temp.setText(str(round(self.tmin, 2)))
self.lineEdit_max_temp.setText(str(round(self.tmax, 2)))
self.update_img_preview()
self.comboBox_img.clear()
self.comboBox_img.addItems(self.ir_imgs)
# Final progress
self.update_progress(nb=100, text="Status: You can now process thermal images!")
except Exception as e:
error(f"Failed to update image list: {str(e)}")
raise ThermogramError(f"Failed to update image list: {str(e)}") from e
def show_info(self):
"""Show application information dialog."""
try:
info_text = f"""
Thermogram v{config.APP_VERSION}
A comprehensive thermal image processing application
for DJI drone thermal imagery.
Features:
- Thermal image visualization
- Temperature analysis
- Measurement tools
- Batch processing
"""
QMessageBox.information(self, "About Thermogram", info_text)
except Exception as e:
error(f"Failed to show info dialog: {str(e)}")
def image_matching(self):
temp_folder = os.path.join(self.app_folder, 'temp')
if not os.path.exists(temp_folder):
os.mkdir(temp_folder)
# get work images
rgb_path = self.work_image.rgb_path_original
ir_path = self.work_image.path
# get initial distortion parameters from the drone model (stored in the image)
# [k1, extend, y - offset, x - offset]
F = self.drone_model.K_ir[0][0]
d_mat = self.drone_model.d_ir
zoom = self.drone_model.zoom
y_off = self.drone_model.y_offset
x_off = self.drone_model.x_offset
print(f'Here are the work values! zoom:{zoom}, y offset:{y_off}, x offset: {x_off}')
dialog = dia.AlignmentDialog(self.work_image, temp_folder, theta=[zoom, y_off, x_off])
if dialog.exec():
# ask options
# Create a QMessageBox
qm = QMessageBox
reply = qm.question(self, '', "Do you want to process all pictures with those new parameters",
qm.StandardButton.Yes | qm.StandardButton.No)
if reply == qm.StandardButton.Yes:
print('Good choice')
# update values
zoom, y_off, x_off = dialog.theta
self.drone_model.zoom = zoom
self.drone_model.y_offset = y_off
self.drone_model.x_offset = x_off
print(f'Re-creating RGB crop with zoom {zoom}')
# re-run all miniatures
text_status = 'creating rgb miniatures...'
self.update_progress(nb=20, text=text_status)
worker_1 = tt.RunnerMiniature(self.list_rgb_paths, self.drone_model, 60,
self.rgb_crop_img_folder, 20,
100)
worker_1.signals.progressed.connect(lambda value: self.update_progress(value))
worker_1.signals.messaged.connect(lambda string: self.update_progress(text=string))
self.__pool.start(worker_1)
worker_1.signals.finished.connect(self.miniat_finish)
else:
pass
# re-print-image
self.update_img_preview(refresh_dual=True)
def miniat_finish(self):
self.update_progress(nb=100, text='Ready...')
self.update_img_preview(refresh_dual=True)
# 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()
new_rect_annot.create_items()
for item in new_rect_annot.ellipse_items:
self.viewer.add_item_from_annot(item)
for item in new_rect_annot.text_items:
self.viewer.add_item_from_annot(item)
# create description name
self.work_image.nb_meas_rect += 1
desc = 'rect_measure_' + str(self.work_image.nb_meas_rect)
new_rect_annot.name = desc
# add annotation to the image annotation list
self.work_image.meas_rect_list.append(new_rect_annot)
rect_cat = self.model.findItems(RECT_MEAS_NAME)
self.add_item_in_tree(rect_cat[0], desc)
self.treeView.expandAll()
# bring data 3d figure
if self.has_rgb:
dialog = dia.Meas3dDialog(new_rect_annot)
dialog.dual_view.load_images_from_path(roi_rgb_path, roi_ir_path)
else:
dialog = dia.Meas3dDialog_simple(new_rect_annot)
dialog.surface_from_image_matplot(self.work_image.colormap, self.work_image.n_colors,
self.work_image.user_lim_col_low,
self.work_image.user_lim_col_high)
if dialog.exec():
pass
# switch back to hand tool
self.hand_pan()
def add_line_meas(self, line_item):
# create annotation (object)
new_line_annot = tt.LineMeas(line_item)
# compute stuff
new_line_annot.compute_data(self.work_image.raw_data_undis)
self.work_image.nb_meas_line += 1
desc = 'line_measure_' + str(self.work_image.nb_meas_line)
new_line_annot.name = desc
# add annotation to the image annotation list
self.work_image.meas_line_list.append(new_line_annot)
line_cat = self.model.findItems(LINE_MEAS_NAME)
self.add_item_in_tree(line_cat[0], desc)
# bring data 3d figure
dialog = dia.MeasLineDialog(new_line_annot.data_roi)
if dialog.exec():
pass
self.hand_pan()
def add_point_meas(self, qpointf):
# create annotation (object)
new_pt_annot = tt.PointMeas(qpointf)
new_pt_annot.temp = self.work_image.raw_data_undis[int(qpointf.y()), int(qpointf.x())]
new_pt_annot.create_items()
self.viewer.add_item_from_annot(new_pt_annot.ellipse_item)
self.viewer.add_item_from_annot(new_pt_annot.text_item)
# create description name
self.work_image.nb_meas_point += 1
desc = 'spot_measure_' + str(self.work_image.nb_meas_point)
new_pt_annot.name = desc
# add annotation to the image annotation list
self.work_image.meas_point_list.append(new_pt_annot)
point_cat = self.model.findItems(POINT_MEAS_NAME)
self.add_item_in_tree(point_cat[0], desc)
self.hand_pan()
# measurements methods
def rectangle_meas(self):
"""Activate rectangle measurement mode."""
try:
if self.actionRectangle_meas.isChecked():
# Activate drawing tool
self.viewer.rect_meas = True
self.viewer.toggleDragMode()
except Exception as e:
error(f"Failed to activate rectangle measurement: {str(e)}")
def point_meas(self):
"""Activate point measurement mode."""
try:
if self.actionSpot_meas.isChecked():
# Activate drawing tool
self.viewer.point_meas = True
self.viewer.toggleDragMode()
except Exception as e:
error(f"Failed to activate point measurement: {str(e)}")
def line_meas(self):
"""Activate line measurement mode."""
try:
if self.actionLine_meas.isChecked():
# Activate drawing tool
self.viewer.line_meas = True
self.viewer.toggleDragMode()
except Exception as e:
error(f"Failed to activate line measurement: {str(e)}")
def remove_annotations(self, type):
if type == 'point':
self.images[self.active_image].meas_point_list = []
elif type == 'line':
self.images[self.active_image].meas_line_list = []
elif type == 'area':
self.images[self.active_image].meas_rect_list = []
self.retrace_items()
# THERMAL-RELATED FUNCTIONS __________________________________________________________________________
def define_options(self):
try:
em = float(self.lineEdit_emissivity.text())
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
# update image data
self.work_image.update_data(copy.deepcopy(self.thermal_param))
self.switch_image_data()
self.update_img_preview()
except ValueError:
QMessageBox.warning(self, "Warning",
"Oops! Some of the values are not valid!")
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(tmin, 2)))
self.lineEdit_max_temp.setText(str(round(tmax, 2)))
self.update_img_preview()
# LOAD AND SAVE ACTIONS ______________________________________________________________________________
def export_anim(self):
# select folder
# Define the starting directory
starting_directory = self.app_folder # Change this to the desired starting path
# Open the file selection dialog for multiple images
files, _ = QFileDialog.getOpenFileNames(
self,
"Select Images",
starting_directory,
"Images (*.png *.xpm *.jpg *.jpeg *.bmp *.tiff *.gif)" # File filter to select image types
)
# If the user selects files, update the label
if files:
print(files)
self.update_progress(nb=20, text="Status: Video creation!")
video_dir = self.app_folder # Adjust the path to your video's folder
video_file = "animation_thermal.mp4" # Adjust to your video file name if needed
video_path = os.path.join(video_dir, video_file)
tt.create_video(files, video_path, 3)
self.update_progress(nb=100, text="Continue analyses!")
msg_box = QMessageBox()
msg_box.setWindowTitle("Video Location")
msg_box.setText(f"Your video is located here:\n{video_path}")
msg_box.exec()
def load_folder_phase1(self):
"""Open a folder dialog and initiate the folder loading process.
This is phase 1 of the folder loading process, which handles:
1. Opening a folder selection dialog
2. Validating the selected folder
3. Setting up project directories
4. Initiating phase 2 of the loading process
"""
# Warning message (new project)
if self.list_rgb_paths != []:
qm = QMessageBox
reply = qm.question(self, '', "Are you sure ? It will create a new project",
qm.StandardButton.Yes | qm.StandardButton.No)
if reply == qm.StandardButton.Yes:
# reset all data
self.full_reset()
else:
return
# Get the image folder from the user
folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
# Detect and organize images
if not folder == '': # if user cancel selection, stop function
self.main_folder = folder
self.app_folder = get_next_available_folder(self.main_folder)
# Update json path
self.json_file = os.path.join(self.app_folder, 'data.json')
# Update status
text_status = 'loading images...'
self.update_progress(nb=0, text=text_status)
# Identify content of the folder
self.list_rgb_paths, self.list_ir_paths, self.list_z_paths = tt.list_th_rgb_images_from_res(
self.main_folder)
# Create some sub folders for storing images
self.original_th_img_folder = os.path.join(self.app_folder, ORIGIN_TH_FOLDER)
# If the sub folders do not exist, create them
if not os.path.exists(self.app_folder):
os.mkdir(self.app_folder)
if not os.path.exists(self.original_th_img_folder):
os.mkdir(self.original_th_img_folder)
# Get drone model
drone_name = tt.get_drone_model(self.list_ir_paths[0])
self.drone_model = tt.DroneModel(drone_name)
# Create 'undistorder' based on drone model
self.ir_undistorder = tt.CameraUndistorter(self.drone_model.ir_xml_path)
# Create dictionary with main information
dictionary = {
"Drone model": drone_name,
"Number of image pairs": str(len(self.list_ir_paths)),
"rgb_paths": self.list_rgb_paths,
"ir_paths": self.list_ir_paths,
"zoom_paths": self.list_z_paths
}
self.write_json(dictionary) # store original images paths in a JSON
text_status = 'copying thermal images...'
self.update_progress(nb=10, text=text_status)
# duplicate thermal images
tt.copy_list_dest(self.list_ir_paths, self.original_th_img_folder)
# does it have RGB?
if not self.list_rgb_paths:
print('No RGB here!')
self.has_rgb = False
self.load_folder_phase2()
else: