-
Notifications
You must be signed in to change notification settings - Fork 39
/
scAnt.py
1720 lines (1394 loc) · 73.3 KB
/
scAnt.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
import datetime
import time
import sys
import traceback
import os
import cgitb
from math import floor
from pathlib import Path
from PyQt5 import QtWidgets, QtGui, QtCore
from GUI.scAnt_GUI_mw import Ui_MainWindow # importing main window of the GUI
from GUI.scAnt_projectSettings_dlg import Ui_Dialog
from GUI.scAnt_cameraSettings_dlg import Ui_CameraDialog
import scripts.project_manager as ymlRW
from scripts.Scanner_Controller import ScannerController
from processStack import getThreads, stack_images, mask_images
from scripts.write_meta_data import write_exif_to_img, get_default_values
"""
Locations of required executables and how to use them:
"""
# qt designer located at:
# C:\Users\PlumStation\Anaconda3\envs\tf-gpu\Lib\site-packages\pyqt5_tools\Qt\bin\designer.exe
# pyuic5 to convert UI to executable python code is located at:
# C:\Users\PlumStation\Anaconda3\envs\tf-gpu\Scripts\pyuic5.exe
# to convert the UI into the required .py file run:
# -x = generates extra code to make ui.py file executable -o = output
# pyuic5.exe -x "I:\3D_Scanner\scAnt\GUI\test.ui" -o "I:\3D_Scanner\scAnt\GUI\test.py"
# or alternatively on Ubuntu
# pyuic5 scAnt_GUI_mw.ui -o scAnt_GUI_mw.py
class WorkerSignals(QtCore.QObject):
'''
Defines the signals available from a running worker thread.
Supported signals are:
finished
No data
error
`tuple` (exctype, value, traceback.format_exc() )
result
`object` data returned from processing, anything
progress
`int` indicating % progress
'''
finished = QtCore.pyqtSignal()
error = QtCore.pyqtSignal(tuple)
result = QtCore.pyqtSignal(object)
progress = QtCore.pyqtSignal(int)
class Worker(QtCore.QRunnable):
'''
Worker thread
Inherits from QRunnable to handler worker thread setup, signals and wrap-up.
:param callback: The function callback to run on this worker thread. Supplied args and
kwargs will be passed through to the runner.
:type callback: function
:param args: Arguments to pass to the callback function
:param kwargs: Keywords to pass to the callback function
'''
def __init__(self, fn, *args, **kwargs):
super(Worker, self).__init__()
# Store constructor arguments (re-used for processing)
self.fn = fn
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
# Add the callback to our kwargs
self.kwargs['progress_callback'] = self.signals.progress
@QtCore.pyqtSlot()
def run(self):
'''
Initialise the runner function with passed args, kwargs.
'''
# Retrieve args/kwargs here; and fire processing using them
try:
result = self.fn(*self.args, **self.kwargs)
except:
traceback.print_exc()
exctype, value = sys.exc_info()[:2]
self.signals.error.emit((exctype, value, traceback.format_exc()))
else:
self.signals.result.emit(result) # Return the result of the processing
finally:
self.signals.finished.emit() # Done
class Dialog(QtWidgets.QDialog):
def __init__(self):
super(Dialog, self).__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
class CameraDialog(QtWidgets.QDialog):
def __init__(self):
super(CameraDialog, self).__init__()
self.ui = Ui_CameraDialog()
self.ui.setupUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
class scAnt_mainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(scAnt_mainWindow, self).__init__()
self.setWindowIcon(QtGui.QIcon(str(Path.cwd().joinpath("images", "scAnt_icon.png"))))
self.liveView = False
self.exit_program = False
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#Initialise Project Settings Dialog window
self.dialog = Dialog()
self.camera_dialog = CameraDialog()
self.configPath = ""
self.name = "test_project"
self.set_project_title()
self.cam = None
self.ui.pushButton_startLiveView.pressed.connect(self.begin_live_view)
self.ui.pushButton_captureImage.pressed.connect(self.capture_image)
self.dialog.ui.lineEdit_projectName.textChanged.connect(self.set_project_title)
self.configPath = ""
self.path_to_external = Path.cwd().joinpath("external")
#Add camera makes to combobox
with open(self.path_to_external.joinpath("cameraMakes.txt"), "r") as f:
self.makes = [make[:-1] for make in f.readlines()]
self.camera_dialog.ui.comboBox_make.addItems(self.makes)
# start thread pool
self.threadpool = QtCore.QThreadPool()
# search for cameras connected to the computer and supported by installed drivers
self.camera_type = None
self.camera_model = None
self.file_format = ".tif"
self.DSLR_read_out = False
self.ActiveSavingProcess = False
# Find FLIR cameras, if attached
try:
from GUI.Live_view_FLIR import customFLIR
self.FLIR = customFLIR()
# camera needs to be initialised before use (self.cam.initialise_camera)
# all detected FLIR cameras are listed in self.cam.device_names
# by default, use the first camera found in the list
self.cam = self.FLIR
self.cam.initialise_camera(select_cam=0)
# now retrieve the name of all found FLIR cameras and add them to the camera selection
for cam in self.cam.device_names:
self.ui.comboBox_selectCamera.addItem(str(cam[0] + " ID: " + cam[1]))
self.camera_type = "FLIR"
# cam.device_names contains both model and serial number
self.camera_model = self.cam.device_names[0][0]
self.FLIR_found = True
self.FLIR_image_queue = []
except IndexError:
message = "No FLIR camera found!"
self.log_info(message)
print(message)
self.FLIR_found = False
self.disable_FLIR_inputs()
except ModuleNotFoundError:
message = "PYSPIN has not been installed - Disabling FLIR camera inputs"
self.log_info(message)
print(message)
self.FLIR_found = False
self.disable_FLIR_inputs()
try:
# TODO add support for the selection of multiple connected DSLR cameras
from GUI.Live_view_DSLR import customDSLR
self.DSLR_initialised = False
self.DSLR = customDSLR()
self.log_info("Found " + str(self.DSLR.camera_model))
self.ui.comboBox_selectCamera.addItem(str(self.DSLR.camera_model))
self.DSLR_found = True
if not self.FLIR_found:
self.ui.stacked_camera_settings.setCurrentIndex(1)
self.cam = self.DSLR
self.camera_type = "DSLR"
self.camera_model = self.DSLR.camera_model
# initialise DSLR by launching an instance of DigiCamControl
worker = Worker(self.launch_DCC_threaded)
worker.signals.finished.connect(self.finished_DCC_launch)
self.threadpool.start(worker)
except:
self.log_info("No DSLR camera found!")
self.DSLR_found = False
# connect camera selection combo box to respective function
self.ui.comboBox_selectCamera.currentTextChanged.connect(self.select_camera)
try:
self.scanner = ScannerController()
# Uncomment if prefered homing on startup
# self.homeX()
# self.homeZ()
self.scanner_initialised = True
except IndexError:
self.scanner_initialised = False
self.disable_stepper_inputs()
warning = "No Stepper Controller found!"
self.log_info(warning)
print(warning)
# FLIR settings
self.ui.checkBox_exposureAuto.stateChanged.connect(self.check_exposure)
self.ui.doubleSpinBox_exposureTime.valueChanged.connect(self.set_exposure_manual)
self.ui.checkBox_gainAuto.stateChanged.connect(self.check_gain)
self.ui.doubleSpinBox_gainLevel.valueChanged.connect(self.set_gain_manual)
self.ui.doubleSpinBox_gamma.valueChanged.connect(self.set_gamma)
self.ui.doubleSpinBox_balanceRatioRed.valueChanged.connect(self.set_balance_ratio)
self.ui.doubleSpinBox_balanceRatioBlue.valueChanged.connect(self.set_balance_ratio)
# TODO Add support for Black level selection
# self.ui.doubleSpinBox_blackLevel.valueChanged.connect(self.set_black_level)
# DSLR settings
self.ui.comboBox_shutterSpeed.currentTextChanged.connect(self.set_shutterspeed)
self.ui.comboBox_aperture.currentTextChanged.connect(self.set_aperture)
self.ui.comboBox_iso.currentTextChanged.connect(self.set_iso)
self.ui.comboBox_whiteBalance.currentTextChanged.connect(self.set_whitebalance)
self.ui.comboBox_compression.currentTextChanged.connect(self.set_compression)
self.ui.checkBox_suggestedValues.stateChanged.connect(self.suggest_values)
# Stepper settings
self.ui.pushButton_xHome.pressed.connect(self.homeX)
self.ui.pushButton_yReset.pressed.connect(self.resetY)
self.ui.pushButton_zHome.pressed.connect(self.homeZ)
self.ui.pushButton_stepperDeEnergise.pressed.connect(self.deEnergise)
self.ui.pushButton_Energise.pressed.connect(self.energise)
self.ui.horizontalSlider_xAxis.sliderReleased.connect(self.moveStepperX)
self.ui.horizontalSlider_xAxis.valueChanged.connect(self.updateDisplayX)
self.ui.horizontalSlider_yAxis.sliderReleased.connect(self.moveStepperY)
self.ui.horizontalSlider_yAxis.valueChanged.connect(self.updateDisplayY)
self.ui.horizontalSlider_zAxis.sliderReleased.connect(self.moveStepperZ)
self.ui.horizontalSlider_zAxis.valueChanged.connect(self.updateDisplayZ)
#Camera Info
self.camera_dialog.ui.comboBox_make.currentIndexChanged.connect(self.change_make)
self.camera_dialog.ui.comboBox_model.currentIndexChanged.connect(self.change_model)
self.camera_dialog.ui.lineEdit_focalLength.editingFinished.connect(self.update_focal_length)
self.ui.pushButton_openCameraInfo.pressed.connect(self.open_camera_settings)
# Update make and model in camera and lens info if cam found
if self.FLIR_found or self.DSLR_found:
with open(self.path_to_external.joinpath("cameraSensors.txt"), "r") as f:
for line in f:
data = line.split(";")
model = data[1]
if data[0] == "FLIR":
data[1] = data[1][:-2]
if data[1].lower().strip() in self.camera_model.lower().strip():
self.camera_dialog.ui.comboBox_make.setCurrentText(data[0])
self.camera_dialog.ui.comboBox_model.setCurrentText(model)
if self.scanner_initialised:
# disable stepper control before they have been homed (except for y axis)
self.deEnergise()
self.homed_X = False
self.homed_Z = False
self.ui.horizontalSlider_xAxis.setEnabled(False)
self.ui.horizontalSlider_zAxis.setEnabled(False)
self.resetY()
# get default scanner Range
self.ui.doubleSpinBox_xMin.setValue(self.scanner.scan_pos[0][0])
self.ui.doubleSpinBox_xMax.setValue(self.scanner.scan_pos[0][-1] + self.scanner.scan_stepSize[0])
self.ui.doubleSpinBox_yMin.setValue(self.scanner.scan_pos[1][0])
self.ui.doubleSpinBox_yMax.setValue(self.scanner.scan_pos[1][-1] + self.scanner.scan_stepSize[1])
self.ui.doubleSpinBox_zMin.setValue(self.scanner.scan_pos[2][0])
self.ui.doubleSpinBox_zMax.setValue(self.scanner.scan_pos[2][-1] + self.scanner.scan_stepSize[2])
# adjust scanner range on input
self.ui.doubleSpinBox_xMin.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_xStep.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_xMax.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_yMin.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_yStep.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_yMax.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_zMin.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_zStep.valueChanged.connect(self.setScannerRange)
self.ui.doubleSpinBox_zMax.valueChanged.connect(self.setScannerRange)
self.images_to_take = len(self.scanner.scan_pos[0]) * len(self.scanner.scan_pos[1]) * len(
self.scanner.scan_pos[2])
self.progress = 0
self.ui.action_runScan.triggered.connect(self.runScanAndReport)
self.xMoving = False
self.yMoving = False
self.zMoving = False
self.posX = 0
self.posY = 0
self.posZ = 0
self.abortScan = False
self.scanInProgress = False
self.showExposure = False
# Scanner output setup
self.dialog.ui.checkBox_includePresets.stateChanged.connect(self.enableConfigEntry)
self.output_location = str(Path.cwd())
self.update_output_location()
self.dialog.ui.pushButton_browseOutput.pressed.connect(self.setOutputLocation)
self.dialog.ui.pushButton_chooseConfig.pressed.connect(self.preloadConfig)
self.dialog.accepted.connect(self.confirmProjectSettings)
self.output_location_folder = Path(self.output_location).joinpath(self.name)
self.ui.pushButton_processingOutput.pressed.connect(self.set_post_location)
self.raw_location = str(Path.cwd().joinpath("test").joinpath("RAW"))
# processing
self.stackImages = False
self.thresholdImages = False
self.stackFocusThreshold = 10.0
self.stackDisplayFocus = False
self.stackSharpen = False
self.ui.checkBox_stackImages.stateChanged.connect(self.enableStacking)
self.ui.checkBox_threshold.stateChanged.connect(self.enableThresholding)
self.maskImages = False
self.maskThreshMin = 215
self.maskThreshMax = 240
self.maskArtifactSizeBlack = 1000
self.maskArtifactSizeWhite = 2000
self.ui.checkBox_maskImages.stateChanged.connect(self.enableMasking)
self.ui.pushButton_runPostProcessing.pressed.connect(self.runPostProcessing)
# once the scan has been started check if new sets of images are available for stacking
self.timerStack = QtCore.QTimer(self)
self.timerStack.timeout.connect(self.checkActiveStackThreads)
self.exif = get_default_values()
self.createCutout = True
# use config file
self.loadedConfig = False
self.ui.action_loadConfig.triggered.connect(self.loadConfig)
self.ui.action_save.triggered.connect(self.writeConfig)
self.ui.action_newProject.triggered.connect(self.openDialog)
self.ui.action_openProject.triggered.connect(self.actionOpenProject)
self.ui.action_darkMode.triggered.connect(self.darkMode)
self.ui.action_lightMode.triggered.connect(self.lightMode)
# stack and mask images
self.maxStackThreads = max(min([int(getThreads() / 6), 2]), 1)
# run no more than 3 stacking threads simultaneously but no less than 1
self.postScanStacking = False
self.activeThreads = 0
self.stackList = []
"""
Stepper Control
"""
def setScannerRange(self):
self.scanner.setScanRange(stepper=0, min=self.ui.doubleSpinBox_xMin.value(),
max=self.ui.doubleSpinBox_xMax.value() + self.ui.doubleSpinBox_xStep.value(),
step=self.ui.doubleSpinBox_xStep.value())
self.scanner.setScanRange(stepper=1, min=self.ui.doubleSpinBox_yMin.value(),
max=self.ui.doubleSpinBox_yMax.value() + self.ui.doubleSpinBox_yStep.value(),
step=self.ui.doubleSpinBox_yStep.value())
self.scanner.setScanRange(stepper=2, min=self.ui.doubleSpinBox_zMin.value(),
max=self.ui.doubleSpinBox_zMax.value() + self.ui.doubleSpinBox_zStep.value(),
step=self.ui.doubleSpinBox_zStep.value())
def updateDisplayX(self):
pos = self.ui.horizontalSlider_xAxis.value()
self.ui.lcdNumber_xAxis.display(pos)
def updateDisplayY(self):
pos = self.ui.horizontalSlider_yAxis.value()
self.ui.lcdNumber_yAxis.display(pos)
def updateDisplayZ(self):
pos = self.ui.horizontalSlider_zAxis.value()
self.ui.lcdNumber_zAxis.display(pos)
def energise(self):
self.scanner.resume()
self.log_info("Energised steppers")
def deEnergise(self):
self.scanner.deEnergise()
self.log_info("De-energised steppers")
self.ui.horizontalSlider_xAxis.setEnabled(False)
self.ui.horizontalSlider_zAxis.setEnabled(False)
self.homed_X = False
self.homed_Z = False
def homeX(self):
self.ui.horizontalSlider_xAxis.setEnabled(False)
self.ui.pushButton_xHome.setEnabled(False)
worker = Worker(self.homeX_threaded)
self.threadpool.start(worker)
worker.signals.finished.connect(self.homeX_finished)
def homeX_threaded(self, progress_callback):
self.scanner.home(0)
self.scanner.getStepperPosition(0)
def homeX_finished(self):
self.log_info("Homed X Axis")
self.ui.horizontalSlider_xAxis.setEnabled(True)
self.ui.pushButton_xHome.setEnabled(True)
self.ui.lcdNumber_xAxis.display(0)
self.ui.horizontalSlider_xAxis.setValue(0)
self.homed_X = True
self.posX = 0
def resetY(self):
self.ui.horizontalSlider_yAxis.setValue(0)
self.updateDisplayY()
self.scanner.home(1)
self.log_info("Reset Y Axis")
def homeZ(self):
self.ui.horizontalSlider_zAxis.setEnabled(False)
self.ui.pushButton_zHome.setEnabled(False)
worker = Worker(self.homeZ_threaded)
self.threadpool.start(worker)
worker.signals.finished.connect(self.homeZ_finished)
def homeZ_threaded(self, progress_callback):
self.scanner.home(2)
self.scanner.getStepperPosition(2)
def homeZ_finished(self):
self.log_info("Homed Z Axis")
self.ui.horizontalSlider_zAxis.setEnabled(True)
self.ui.pushButton_zHome.setEnabled(True)
self.ui.lcdNumber_zAxis.display(0)
self.ui.horizontalSlider_zAxis.setValue(0)
self.homed_Z = True
self.posZ = 0
def moveStepperX(self):
self.xMoving = True
self.ui.horizontalSlider_xAxis.setEnabled(False)
self.ui.pushButton_xHome.setEnabled(False)
worker = Worker(self.moveStepperX_threaded)
self.threadpool.start(worker)
worker.signals.finished.connect(self.moveStepperX_finished)
def moveStepperX_threaded(self, progress_callback):
pos = self.ui.horizontalSlider_xAxis.value()
self.scanner.moveToPosition(stepper=0, pos=pos)
self.posX = pos
def moveStepperX_finished(self):
self.ui.horizontalSlider_xAxis.setEnabled(True)
self.ui.pushButton_xHome.setEnabled(True)
self.xMoving = False
def moveStepperY(self):
self.yMoving = True
self.ui.pushButton_yReset.setEnabled(False)
self.ui.horizontalSlider_yAxis.setEnabled(False)
worker = Worker(self.moveStepperY_threaded)
self.threadpool.start(worker)
worker.signals.finished.connect(self.moveStepperY_finished)
def moveStepperY_threaded(self, progress_callback):
pos = self.ui.horizontalSlider_yAxis.value()
self.scanner.moveToPosition(stepper=1, pos=pos)
self.posY = pos
def moveStepperY_finished(self):
self.ui.horizontalSlider_yAxis.setEnabled(True)
self.ui.pushButton_yReset.setEnabled(True)
self.yMoving = False
def moveStepperZ(self):
self.zMoving = True
self.ui.pushButton_zHome.setEnabled(False)
self.ui.horizontalSlider_zAxis.setEnabled(False)
worker = Worker(self.moveStepperZ_threaded)
self.threadpool.start(worker)
worker.signals.finished.connect(self.moveStepperZ_finished)
def moveStepperZ_threaded(self, progress_callback):
pos = self.ui.horizontalSlider_zAxis.value()
self.scanner.moveToPosition(stepper=2, pos=pos)
self.posZ = pos
def moveStepperZ_finished(self):
self.ui.horizontalSlider_zAxis.setEnabled(True)
self.ui.pushButton_zHome.setEnabled(True)
self.zMoving = False
"""
Camera Settings
"""
def select_camera(self):
self.disable_FLIR_inputs()
self.disable_DSLR_inputs()
selected_camera = self.ui.comboBox_selectCamera.currentText()
self.log_info("Selected camera: " + str(selected_camera))
# stop the live view if currently in use
if self.liveView:
self.begin_live_view() # sets live view false if already running
# de-initialised previous FLIR, if it was in use
if self.camera_type == "FLIR":
# de-initialise the previous camera before setting up the newly selected one
self.cam.deinitialise_camera()
# new camera -> FLIR
if selected_camera.split(" ")[0] == "Blackfly":
for ID, FLIR in enumerate(self.FLIR.device_names):
if self.ui.comboBox_selectCamera.currentText() == str(FLIR[0] + " ID: " + FLIR[1]):
self.cam = self.FLIR
self.cam.initialise_camera(select_cam=ID)
self.log_info("Camera in use: " + str(FLIR[0] + " ID: " + FLIR[1]))
self.camera_type = "FLIR"
self.begin_live_view()
self.camera_model = self.FLIR.device_names[ID][0]
self.enable_FLIR_inputs()
self.file_format = ".tif"
# new camera -> DSLR
else:
self.cam = self.DSLR
self.camera_type = "DSLR"
self.camera_model = self.DSLR.camera_model
# initialise DSLR by launching an instance of DigiCamControl
worker = Worker(self.launch_DCC_threaded)
worker.signals.finished.connect(self.finished_DCC_launch)
self.threadpool.start(worker)
def launch_DCC_threaded(self, progress_callback):
self.cam.initialise_camera()
self.DSLR_initialised = True
def finished_DCC_launch(self):
self.log_info("Launched DCC and retrieved camera settings")
self.enable_DSLR_inputs()
#Camera Info
def open_camera_settings(self):
self.camera_dialog.show()
def change_make(self):
self.camera_dialog.ui.comboBox_model.clear()
self.make = self.camera_dialog.ui.comboBox_make.currentText()
if self.make in self.makes:
with open(self.path_to_external.joinpath("cameraSensors.txt"), "r") as file:
for line in file:
if line.startswith(self.make):
self.camera_dialog.ui.comboBox_model.addItem(line.split(";")[1])
def change_model(self):
self.model = self.camera_dialog.ui.comboBox_model.currentText()
with open(self.path_to_external.joinpath("cameraSensors.txt"), "r") as file:
for line in file:
data = line.split(";")
if data[1] == self.model:
self.sensor_width = data[2]
self.camera_dialog.ui.lineEdit_sensorWidth.setText(self.sensor_width)
self.update_focal_length()
def update_focal_length(self):
focal_length = self.camera_dialog.ui.lineEdit_focalLength.text()
if focal_length and self.model:
try:
standard_fl = floor(36 * float(focal_length) / float(self.sensor_width))
self.camera_dialog.ui.lineEdit_focalLengthIn35mmFormat.setText(str(standard_fl))
except Exception as error_sensorWidth:
print(error_sensorWidth)
# FLIR Settings
def check_exposure(self):
if self.ui.checkBox_exposureAuto.isChecked():
self.set_exposure_auto()
else:
self.set_exposure_manual()
def set_exposure_auto(self):
self.cam.reset_exposure()
self.ui.label_exposureTime.setEnabled(False)
self.ui.doubleSpinBox_exposureTime.setEnabled(False)
self.log_info("Enabled automatic exposure")
def set_exposure_manual(self):
self.ui.label_exposureTime.setEnabled(True)
self.ui.doubleSpinBox_exposureTime.setEnabled(True)
value = self.ui.doubleSpinBox_exposureTime.value()
if value is not None:
self.log_info("Exposure time set to " + str(value) + " [us]")
self.cam.configure_exposure(float(value))
def check_gain(self):
if self.ui.checkBox_gainAuto.isChecked():
self.set_gain_auto()
else:
self.set_gain_manual()
def set_gain_auto(self):
self.cam.reset_gain()
self.ui.label_gainLevel.setEnabled(False)
self.ui.doubleSpinBox_gainLevel.setEnabled(False)
self.log_info("Enabled automatic exposure")
def set_gain_manual(self):
self.ui.label_gainLevel.setEnabled(True)
self.ui.doubleSpinBox_gainLevel.setEnabled(True)
value = self.ui.doubleSpinBox_gainLevel.value()
if value is not None:
self.log_info("Gain level set to " + str(value) + " [dB]")
self.cam.set_gain(float(value))
def set_gamma(self):
value = self.ui.doubleSpinBox_gamma.value()
if value is not None:
self.log_info("Gain set to " + str(value))
self.cam.set_gamma(float(value))
def set_balance_ratio(self):
value_red = self.ui.doubleSpinBox_balanceRatioRed.value()
value_blue = self.ui.doubleSpinBox_balanceRatioBlue.value()
if value_red is not None and value_blue is not None:
self.log_info("White balance ratio set to " + str(value_red) + " and " + str(value_blue))
self.cam.set_white_balance(float(value_red), float(value_blue))
def set_black_level(self):
# TODO -> not yet functional, error thrown from PySpin
value = self.ui.doubleSpinBox_blackLevel.value()
if value is not None:
self.log_info("Gain set to " + str(value))
self.cam.set_black_level(float(value))
def update_live_view(self, progress_callback):
while self.liveView and self.camera_type == "FLIR":
try:
img = self.cam.live_view()
#keep refence to original image
temp = img
# if enabled, display exposure as histogram and highlight over exposed areas
if self.ui.checkBox_highlightExposure.isChecked():
img = self.cam.showExposure(img)
#if enabled, display focus score overlay
if self.ui.checkBox_focusOverlay.isChecked():
img = self.cam.showFocus(temp, img)
live_img = QtGui.QImage(img, img.shape[1], img.shape[0], QtGui.QImage.Format_RGB888).rgbSwapped()
live_img_pixmap = QtGui.QPixmap.fromImage(live_img)
# Setup pixmap with the acquired image
live_img_scaled = live_img_pixmap.scaled(self.ui.label_liveView.width(),
self.ui.label_liveView.height(),
QtCore.Qt.KeepAspectRatio)
# Set the pixmap onto the label
self.ui.label_liveView.setPixmap(live_img_scaled)
# Align the label to center
self.ui.label_liveView.setAlignment(QtCore.Qt.AlignCenter)
except AttributeError:
print("Live view ended")
self.ui.label_liveView.setText("Live view disabled.")
# DSLR settings
def set_shutterspeed(self):
if not self.DSLR_read_out:
self.cam.set_shutterspeed(self.ui.comboBox_shutterSpeed.currentText())
self.log_info("Set shutter speed to " + self.ui.comboBox_shutterSpeed.currentText())
def set_aperture(self):
if not self.DSLR_read_out:
self.cam.set_aperture(self.ui.comboBox_aperture.currentText())
self.log_info("Set aperture to " + self.ui.comboBox_aperture.currentText())
def set_iso(self):
if not self.DSLR_read_out:
self.cam.set_iso(self.ui.comboBox_iso.currentText())
self.log_info("Set iso to " + self.ui.comboBox_iso.currentText())
def set_whitebalance(self):
if not self.DSLR_read_out:
self.cam.set_whitebalance(self.ui.comboBox_whiteBalance.currentText())
self.log_info("Set white balance to " + self.ui.comboBox_whiteBalance.currentText())
def set_compression(self):
if not self.DSLR_read_out:
self.cam.set_compression(self.ui.comboBox_compression.currentText())
self.log_info("Set compression to " + self.ui.comboBox_compression.currentText())
def suggest_values(self):
try:
img = self.cam.live_view()
if self.ui.checkBox_suggestedValues.isChecked():
(min_val, max_val) = self.cam.suggest_values(img)
self.ui.spinBox_thresholdMin.setValue(min_val)
self.ui.spinBox_thresholdMax.setValue(max_val)
except:
print("No camera found!")
def get_DSLR_file_ending(self):
# first get the current compression setting
compression_setting = self.cam.get_current_setting("compressionsetting")
if compression_setting.split(" ")[0] == "JPEG":
self.file_format = ".jpg"
elif compression_setting.split(" ")[0] == "RAW":
# different cameras use different RAW format endings
brand = self.camera_model.split(" ")[0]
# Nikon cameras are simply named D###
if brand[0] == "D":
self.file_format = ".nef"
# Canon cameras use their brand name directly
elif brand == "Canon":
self.file_format = ".CR2"
else:
self.file_format = ".jpg"
self.log_warning("Unknown image file format! Using JPEG as default!")
# Info & Threading functions
def log_info(self, info):
now = datetime.datetime.now()
self.ui.listWidget_log.addItem(now.strftime("%H:%M:%S") + " [INFO] " + info)
self.ui.listWidget_log.sortItems(QtCore.Qt.DescendingOrder)
def log_warning(self, warning):
now = datetime.datetime.now()
self.ui.listWidget_log.addItem(now.strftime("%H:%M:%S") + " [ERROR] " + warning)
self.ui.listWidget_log.sortItems(QtCore.Qt.DescendingOrder)
def thread_complete(self):
#Remove any remaining contour files
for file in os.listdir(self.output_location_folder.joinpath("stacked")):
if file.endswith("contour.png"):
os.remove(self.output_location_folder.joinpath("stacked").joinpath(file))
self.scanInProgress = False
self.changeInputState()
self.log_info("Scanning completed!")
def begin_live_view(self):
if not self.liveView:
self.ui.checkBox_highlightExposure.setEnabled(True)
self.ui.checkBox_focusOverlay.setEnabled(True)
self.ui.label_highlightExposure.setEnabled(True)
self.ui.label_focusOverlay.setEnabled(True)
self.log_info("Began camera live view")
self.ui.pushButton_startLiveView.setText("Stop Live View")
self.liveView = True
if self.camera_type == "FLIR":
worker = Worker(self.update_live_view)
self.threadpool.start(worker)
else:
# starts live view in external Window
self.ui.label_liveView.setText("Live view opened in external DCC window!")
self.cam.start_live_view()
else:
self.ui.checkBox_highlightExposure.setEnabled(False)
self.ui.checkBox_focusOverlay.setEnabled(False)
self.ui.label_highlightExposure.setEnabled(False)
self.ui.label_focusOverlay.setEnabled(False)
self.ui.label_liveView.setText("Live view disabled.")
self.ui.pushButton_startLiveView.setText("Start Live View")
self.log_info("Ended camera live view")
self.liveView = False
if self.camera_type == "DSLR":
self.cam.stop_live_view()
def capture_image(self):
now = datetime.datetime.now()
self.create_output_folders()
# create unique filename
file_name = str(self.output_location_folder.joinpath(now.strftime("%Y-%m-%d_%H-%M-%S-%MS_" + self.file_format)))
self.cam.capture_image(file_name)
self.log_info("Captured " + file_name)
def create_output_folders(self):
self.output_location_folder = Path(self.output_location).joinpath(self.name)
if not os.path.exists(self.output_location_folder):
os.makedirs(self.output_location_folder)
self.log_info("Created folder at:" + str(self.output_location_folder))
if not os.path.exists(self.output_location_folder.joinpath("RAW")):
os.makedirs(self.output_location_folder.joinpath("RAW"))
if not os.path.exists(self.output_location_folder.joinpath("stacked")):
os.makedirs(self.output_location_folder.joinpath("stacked"))
"""
Scanner Setup
"""
def getProgress(self):
self.progress = min(int(100 * (self.images_taken / self.images_to_take)), 100)
def set_project_title(self):
self.setWindowTitle("scAnt: " + self.name)
def setOutputLocation(self):
new_location = QtWidgets.QFileDialog.getExistingDirectory(self, "Choose output location",
str(Path.cwd()))
if new_location:
self.output_location = new_location
self.update_output_location()
def set_post_location(self):
new_location = QtWidgets.QFileDialog.getExistingDirectory(self, "Choose RAW images folder to process",
str(Path.cwd()))
if new_location:
self.raw_location = new_location
self.update_raw_location()
def runPostProcessing(self):
config_present = False
raw_folder_loc = self.raw_location
parent = Path(raw_folder_loc).parent
for file in os.listdir(parent):
if file.endswith(".yaml"):
config_present = True
config_file = file
if config_present:
config_location = parent.joinpath(config_file)
config = ymlRW.read_config_file(config_location)
focus_threshold = config["stacking"]["threshold"]
sharpen = config["stacking"]["additional_sharpening"]
exif = config["exif_data"]
mask_images_check = config["masking"]["mask_images"]
mask_thresh_min = config["masking"]["mask_thresh_min"]
mask_thresh_max = config["masking"]["mask_thresh_max"]
mask_artifact_size_black = config["masking"]["min_artifact_size_black"]
mask_artifact_size_white = config["masking"]["min_artifact_size_white"]
stacks = []
stack = []
prev_xy = ""
for i,file in enumerate(os.listdir(raw_folder_loc)):
xy_pos = file[:-10]
if xy_pos != prev_xy and i != 0:
stacks.append(stack)
stack = []
stack.append(str(Path(raw_folder_loc).joinpath(file)))
prev_xy = xy_pos
for stack in stacks:
try:
stacked_output = stack_images(input_paths=stack, check_focus = self.thresholdImages, threshold=focus_threshold,
sharpen=sharpen)
write_exif_to_img(img_path=stacked_output[0], custom_exif_dict=exif)
if mask_images_check:
mask_images(input_paths=stacked_output, min_rgb=mask_thresh_min, max_rgb=mask_thresh_max,
min_bl=mask_artifact_size_black, min_wh=mask_artifact_size_white, create_cutout=True)
if self.createCutout:
write_exif_to_img(img_path=str(stacked_output[0])[:-4] + '_cutout.jpg', custom_exif_dict=self.exif)
except Exception as e:
print(e)
print("Post Processing Completed")
else:
print("No config file found!")
def loadConfig(self):
if self.configPath == "":
file = QtWidgets.QFileDialog.getOpenFileName(self, "Load existing config file",
str(Path.cwd()), "config file (*.yaml)")
config_location = file[0]
else:
config_location = self.configPath
if config_location:
# if a file has been selected, convert it into a Path object
config_location = Path(config_location)
config = ymlRW.read_config_file(config_location)
# check if the camera type in the config file matches the connected/selected camera type
if config["general"]["camera_type"] == self.camera_type:
# camera_settings:
if config["general"]["camera_type"] == "FLIR":
# FLIR
self.ui.doubleSpinBox_exposureTime.setValue(config["camera_settings"]["exposure_time"])
if config["camera_settings"]["exposure_auto"]:
self.ui.checkBox_exposureAuto.setChecked(True)
else:
self.set_exposure_manual()
self.ui.doubleSpinBox_gainLevel.setValue(config["camera_settings"]["gain_level"])
if config["camera_settings"]["gain_auto"]:
self.ui.checkBox_gainAuto.setChecked(True)
else:
self.ui.checkBox_gainAuto.setChecked(False)
self.ui.doubleSpinBox_gamma.setValue(config["camera_settings"]["gamma"])
self.set_gamma()
self.ui.doubleSpinBox_balanceRatioRed.setValue(config["camera_settings"]["balance_ratio_red"])
self.ui.doubleSpinBox_balanceRatioBlue.setValue(config["camera_settings"]["balance_ratio_blue"])
self.set_balance_ratio()
# self.ui.doubleSpinBox_blackLevel.setValue(config["camera_settings"]["black_level"])
# self.set_black_level()
else:
# DSLR
self.ui.comboBox_shutterSpeed.setCurrentIndex(
self.ui.comboBox_shutterSpeed.findText(str(config["camera_settings"]["shutterspeed"])))
self.ui.comboBox_aperture.setCurrentIndex(
self.ui.comboBox_aperture.findText(str(config["camera_settings"]["aperture"])))