-
Notifications
You must be signed in to change notification settings - Fork 7
/
lumaviewpro.py
5912 lines (4576 loc) · 211 KB
/
lumaviewpro.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
'''
MIT License
Copyright (c) 2024 Etaluma, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
```
This open source software was developed for use with Etaluma microscopes.
AUTHORS:
Kevin Peter Hickerson, The Earthineering Company
Anna Iwaniec Hickerson, Keck Graduate Institute
Bryan Tiedemann, The Earthineering Company
Gerard Decker, The Earthineering Company
'''
# General
import copy
import logging
import datetime
from datetime import datetime as date_time
import math
import os
import pathlib
import matplotlib.pyplot as plt
from matplotlib.dates import ConciseDateFormatter
import numpy as np
import pandas as pd
import time
import json
import subprocess
import sys
import typing
import shutil
import userpaths
############################################################################
#---------------------Directory Initialization-----------------------------#
############################################################################
abspath = os.path.abspath(__file__)
basename = os.path.basename(__file__)
script_path = abspath[:-len(basename)]
print(f"Script Location: {script_path}")
os.chdir(script_path)
# The version.txt file is in the same directory as the actual script, so making sure it can find the version file.
global version
global windows_machine
windows_machine = False
if os.name == "nt":
windows_machine = True
version = ""
try:
with open("version.txt") as f:
version = f.readlines()[0].strip()
except:
pass
PROTOCOL_DATA_DIR_NAME = "ProtocolData"
try:
with open("marker.lvpinstalled") as f:
lvp_installed = True
except:
lvp_installed = False
if windows_machine and (lvp_installed == True):
print("Machine-Type - WINDOWS")
documents_folder = userpaths.get_my_documents()
os.chdir(documents_folder)
lvp_appdata = os.path.join(documents_folder, f"LumaViewPro {version}")
if os.path.exists(lvp_appdata):
pass
else:
os.mkdir(lvp_appdata)
source_path = lvp_appdata
print(f"Data Location: {source_path}")
os.chdir(source_path)
if os.path.exists(os.path.join(lvp_appdata, "data")):
pass
else:
shutil.copytree(os.path.join(script_path, "data"), os.path.join(lvp_appdata, "data"))
if os.path.exists(os.path.join(lvp_appdata, "logs")):
pass
else:
shutil.copytree(os.path.join(script_path, "logs"), os.path.join(lvp_appdata, "logs"))
elif windows_machine and (lvp_installed == False):
print("Machine-Type - WINDOWS (not installed)")
source_path = script_path
else:
print("Machine-Type - NON-WINDOWS")
source_path = script_path
############################################################################
#--------------------------------------------------------------------------#
############################################################################
from lvp_logger import logger
import tkinter
from tkinter import filedialog, Tk
from plyer import filechooser
import imagej.doctor
import imagej
imagej.doctor.checkup()
import scyjava
import modules.profiling_utils as profiling_utils
global profiling_helper
profiling_helper = None
if getattr(sys, 'frozen', False):
import pyi_splash # type: ignore
pyi_splash.update_text("")
# Deactivate kivy logging
#os.environ["KIVY_NO_CONSOLELOG"] = "1"
# Kivy configurations
# Configurations must be set befor Kivy is imported
from kivy.config import Config
Config.set('input', 'mouse', 'mouse, disable_multitouch')
Config.set('graphics', 'resizable', True) # this seemed to have no effect so may be unnessesary
Config.set('kivy', 'exit_on_escape', '0')
# if fixed size at launch
#Config.set('graphics', 'width', '1920')
#Config.set('graphics', 'height', '1080')
# if maximized at launch
Config.set('graphics', 'window_state', 'maximized')
import kivy
kivy.require("2.1.0")
from kivy.app import App
from kivy.factory import Factory
from kivy.graphics import RenderContext
from kivy.input.motionevent import MotionEvent
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty, ListProperty
#from kivy.properties import BoundedNumericProperty, ColorProperty, OptionProperty, NumericProperty
from kivy.clock import Clock
from kivy.metrics import dp
#from kivy.animation import Animation
from kivy.graphics import Line, Color, Rectangle, Ellipse
from kivy_garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
# User Interface
from kivy.uix.accordion import AccordionItem
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scatter import Scatter
from kivy.uix.widget import Widget
from kivy.uix.slider import Slider
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.popup import Popup
from kivy.uix.label import Label
# Video Related
from kivy.graphics.texture import Texture
# User Interface Custom Widgets
from custom_widgets.range_slider import RangeSlider
from custom_widgets.progress_popup import show_popup
#post processing
from image_stitcher import image_stitcher
from modules.video_builder import VideoBuilder
from modules.tiling_config import TilingConfig
import modules.common_utils as common_utils
import labware
from modules.autofocus_executor import AutofocusExecutor
from modules.stitcher import Stitcher
import modules.binning as binning
from modules.composite_generation import CompositeGeneration
from modules.contrast_stretcher import ContrastStretcher
import modules.coord_transformations as coord_transformations
import modules.labware_loader as labware_loader
import modules.objectives_loader as objectives_loader
from modules.protocol import Protocol
from modules.sequenced_capture_executor import SequencedCaptureExecutor
from modules.sequenced_capture_run_modes import SequencedCaptureRunMode
from modules.stack_builder import StackBuilder
from modules.zstack_config import ZStackConfig
from modules.json_helper import CustomJSONizer
from modules.timedelta_formatter import strfdelta
import modules.imagej_helper as imagej_helper
import modules.zprojector as zprojector
from modules.video_writer import VideoWriter
import cv2
import skimage
# Hardware
import lumascope_api
import post_processing
import image_utils
import image_utils_kivy
global lumaview
global settings
global cell_count_content
global graphing_controls
global wellplate_loader
wellplate_loader = None
global objective_helper
objective_helper = None
global coordinate_transformer
coordinate_transformer = None
global ij_helper
ij_helper = None
global sequenced_capture_executor
sequenced_capture_executor = None
# global autofocus_executor
# autofocus_executor = None
global live_histo_setting
live_histo_setting = False
global last_save_folder
last_save_folder = None
global stage
stage = None
global ENGINEERING_MODE
ENGINEERING_MODE = False
global debug_counter
debug_counter = 0
start_str = time.strftime("%Y %m %d %H_%M_%S")
start_str = str(int(round(time.time() * 1000)))
global focus_round
focus_round = 0
def set_last_save_folder(dir: pathlib.Path | None):
if dir is None:
return
global last_save_folder
last_save_folder=dir
def focus_log(positions, values):
global focus_round
if False:
os.chdir(source_path)
try:
file = open('./logs/focus_log.txt', 'a')
except:
if not os.path.isdir('./logs'):
raise FileNotFoundError("Couldn't find 'logs' directory.")
else:
raise
for i, p in enumerate(positions):
mssg = str(focus_round) + '\t' + str(p) + '\t' + str(values[i]) + '\n'
file.write(mssg)
file.close()
focus_round += 1
def _handle_ui_for_leds_off():
global lumaview
for layer in common_utils.get_layers():
lumaview.ids['imagesettings_id'].ids[layer].ids['enable_led_btn'].state = 'normal'
def _handle_ui_for_led(layer: str, enabled: bool, **kwargs):
global lumaview
if enabled:
state = "down"
else:
state = "normal"
lumaview.ids['imagesettings_id'].ids[layer].ids['enable_led_btn'].state = state
def scope_leds_off():
global lumaview
if not lumaview.scope.led:
logger.warning('[LVP Main ] LED controller not available.')
return
lumaview.scope.leds_off()
logger.info('[LVP Main ] lumaview.scope.leds_off()')
_handle_ui_for_leds_off()
def is_image_saving_enabled() -> bool:
if ENGINEERING_MODE == True:
if lumaview.ids['motionsettings_id'].ids['protocol_settings_id'].ids['protocol_disable_image_saving_id'].active:
return False
return True
def _update_step_number_callback(step_num: int):
protocol_settings = lumaview.ids['motionsettings_id'].ids['protocol_settings_id']
protocol_settings.curr_step = step_num-1
protocol_settings.update_step_ui()
def go_to_step(
protocol: Protocol,
step_idx: int,
ignore_auto_gain: bool = False,
include_move: bool = True
):
num_steps = protocol.num_steps()
protocol_settings = lumaview.ids['motionsettings_id'].ids['protocol_settings_id']
if num_steps <= 0:
protocol_settings.curr_step = -1
protocol_settings.update_step_ui()
return
if (step_idx < 0) or (step_idx >= num_steps):
protocol_settings.curr_step = -1
protocol_settings.update_step_ui()
return
step = protocol.step(idx=step_idx)
protocol_settings.ids['step_name_input'].text = step["Name"]
if step['Name'] == '':
step_name = common_utils.generate_default_step_name(
well_label=step["Well"],
color=step['Color'],
z_height_idx=step['Z-Slice'],
tile_label=step['Tile']
)
protocol_settings.ids['step_name_input'].hint_text = step_name
# Convert plate coordinates to stage coordinates
if include_move:
_, labware = get_selected_labware()
sx, sy = coordinate_transformer.plate_to_stage(
labware=labware,
stage_offset=settings['stage_offset'],
px=step["X"],
py=step["Y"]
)
# Move into position
if lumaview.scope.motion.driver:
move_absolute_position('X', sx)
move_absolute_position('Y', sy)
move_absolute_position('Z', step["Z"])
else:
logger.warning('[LVP Main ] Motion controller not available.')
color = step['Color']
layer = lumaview.ids['imagesettings_id'].ids[color]
# open ImageSettings
lumaview.ids['imagesettings_id'].ids['toggle_imagesettings'].state = 'down'
lumaview.ids['imagesettings_id'].toggle_settings()
# set accordion item to corresponding channel
id = f"{color}_accordion"
lumaview.ids['imagesettings_id'].ids[id].collapse = False
# set autofocus checkbox
logger.info(f'[LVP Main ] autofocus: {step["Auto_Focus"]}')
settings[color]['autofocus'] = step['Auto_Focus']
layer.ids['autofocus'].active = step['Auto_Focus']
# set false_color checkbox
logger.info(f'[LVP Main ] false_color: {step["False_Color"]}')
settings[color]['false_color'] = step['False_Color']
layer.ids['false_color'].active = step['False_Color']
# set illumination settings, text, and slider
logger.info(f'[LVP Main ] ill: {step["Illumination"]}')
settings[color]['ill'] = step["Illumination"]
layer.ids['ill_text'].text = str(step["Illumination"])
layer.ids['ill_slider'].value = float(step["Illumination"])
# set gain settings, text, and slider
logger.info(f'[LVP Main ] gain: {step["Gain"]}')
settings[color]['gain'] = step["Gain"]
layer.ids['gain_text'].text = str(step["Gain"])
layer.ids['gain_slider'].value = float(step["Gain"])
# set auto_gain checkbox
logger.info(f'[LVP Main ] auto_gain: {step["Auto_Gain"]}')
settings[color]['auto_gain'] = step["Auto_Gain"]
layer.ids['auto_gain'].active = step["Auto_Gain"]
# set exposure settings, text, and slider
logger.info(f'[LVP Main ] exp: {step["Exposure"]}')
settings[color]['exp'] = step["Exposure"]
layer.ids['exp_text'].text = str(step["Exposure"])
layer.ids['exp_slider'].value = float(step["Exposure"])
# acquire type
for acquire_sel in ('acquire_video', 'acquire_image', 'acquire_none'):
layer.ids[acquire_sel].active = False
if step['Acquire'] == 'video':
layer.ids['acquire_video'].active = True
elif step['Acquire'] == 'image':
layer.ids['acquire_image'].active = True
else:
layer.ids['acquire_none'].active = True
layer.apply_settings(ignore_auto_gain=ignore_auto_gain)
def get_binning_from_ui() -> int:
try:
return int(lumaview.ids['motionsettings_id'].ids['microscope_settings_id'].ids['binning_spinner'].text)
except:
return 1
def get_zstack_params() -> dict:
zstack_settings = lumaview.ids['motionsettings_id'].ids['verticalcontrol_id'].ids['zstack_id']
range = float(zstack_settings.ids['zstack_range_id'].text)
step_size = float(zstack_settings.ids['zstack_stepsize_id'].text)
z_reference = common_utils.convert_zstack_reference_position_setting_to_config(
text_label=zstack_settings.ids['zstack_spinner'].text
)
return {
'range': range,
'step_size': step_size,
'z_reference': z_reference,
}
def get_zstack_positions() -> tuple[bool, dict]:
config = get_zstack_params()
current_pos = lumaview.scope.get_current_position('Z')
zstack_config = ZStackConfig(
range=config['range'],
step_size=config['step_size'],
current_z_reference=config['z_reference'],
current_z_value=current_pos
)
if zstack_config.number_of_steps() <= 0:
return False, {None: None}
return True, zstack_config.step_positions()
def get_layer_configs(
specific_layers: list | None = None,
) -> dict[dict]:
layer_configs = {}
for layer in common_utils.get_layers():
if (specific_layers is not None) and (layer not in specific_layers):
continue
layer_configs[layer] = {}
layer_settings = settings[layer]
acquire = layer_settings['acquire']
video_config = layer_settings['video_config']
autofocus = layer_settings['autofocus']
false_color = layer_settings['false_color']
illumination = round(layer_settings['ill'], common_utils.max_decimal_precision('illumination'))
gain = round(layer_settings['gain'], common_utils.max_decimal_precision('gain'))
auto_gain = common_utils.to_bool(layer_settings['auto_gain'])
exposure = round(layer_settings['exp'], common_utils.max_decimal_precision('exposure'))
focus = layer_settings['focus']
layer_configs[layer] = {
'acquire': acquire,
'video_config': video_config,
'autofocus': autofocus,
'false_color': false_color,
'illumination': illumination,
'gain': gain,
'auto_gain': auto_gain,
'exposure': exposure,
'focus': focus
}
return layer_configs
def get_active_layer_config() -> tuple[str, dict]:
c_layer = None
for layer in common_utils.get_layers():
accordion = layer + '_accordion'
if lumaview.ids['imagesettings_id'].ids[accordion].collapse == False:
c_layer = layer
break
if c_layer is None:
raise Exception("No layer currently selected")
layer_configs = get_layer_configs(
specific_layers=[c_layer]
)
return c_layer, layer_configs[c_layer]
def get_current_plate_position():
if not lumaview.scope.motion.driver:
logger.error(f"Cannot retrieve current plate position")
return {
'x': 0,
'y': 0,
'z': 0
}
pos = lumaview.scope.get_current_position(axis=None)
_, labware = get_selected_labware()
px, py = coordinate_transformer.stage_to_plate(
labware=labware,
stage_offset=settings['stage_offset'],
sx=pos['X'],
sy=pos['Y'],
)
return {
'x': round(px, common_utils.max_decimal_precision('x')),
'y': round(py, common_utils.max_decimal_precision('y')),
'z': round(pos['Z'], common_utils.max_decimal_precision('z'))
}
def get_current_frame_dimensions() -> dict:
microscope_settings = lumaview.ids['motionsettings_id'].ids['microscope_settings_id']
try:
frame_width = int(microscope_settings.ids['frame_width_id'].text)
frame_height = int(microscope_settings.ids['frame_height_id'].text)
except:
raise ValueError(f"Invalid value for frame width/height")
frame = {
'width': frame_width,
'height': frame_height
}
return frame
def get_protocol_time_params() -> dict:
protocol_settings = lumaview.ids['motionsettings_id'].ids['protocol_settings_id']
try:
period = float(protocol_settings.ids['capture_period'].text)
except:
period = 1
period = datetime.timedelta(minutes=period)
try:
duration = float(protocol_settings.ids['capture_dur'].text)
except:
duration = 1
duration = datetime.timedelta(hours=duration)
return {
'period': period,
'duration': duration
}
def get_selected_labware() -> tuple[str, labware.WellPlate]:
protocol_settings = lumaview.ids['motionsettings_id'].ids['protocol_settings_id']
labware_id = protocol_settings.ids['labware_spinner'].text
if len(labware_id) < 1:
labware_id = settings['protocol']['labware']
try:
labware = wellplate_loader.get_plate(plate_key=labware_id)
return labware_id, labware
except Exception as e:
logger.error("LVP Main: Settings file issue. Replace file with a known working version")
logger.error(e)
def get_image_capture_config_from_ui() -> dict:
microscope_settings = lumaview.ids['motionsettings_id'].ids['microscope_settings_id']
output_format = {
'live': microscope_settings.ids['live_image_output_format_spinner'].text,
'sequenced': microscope_settings.ids['sequenced_image_output_format_spinner'].text,
}
use_full_pixel_depth = lumaview.ids['viewer_id'].ids['scope_display_id'].use_full_pixel_depth
return {
'output_format': output_format,
'use_full_pixel_depth': use_full_pixel_depth,
}
def get_sequenced_capture_config_from_ui() -> dict:
objective_id, _ = get_current_objective_info()
time_params = get_protocol_time_params()
labware_id, _ = get_selected_labware()
protocol_settings = lumaview.ids['motionsettings_id'].ids['protocol_settings_id']
tiling = protocol_settings.ids['tiling_size_spinner'].text
use_zstacking = protocol_settings.ids['acquire_zstack_id'].active
frame_dimensions = get_current_frame_dimensions()
zstack_params = get_zstack_params()
layer_configs = get_layer_configs()
config = {
'labware_id': labware_id,
'objective_id': objective_id,
'zstack_params': zstack_params,
'use_zstacking': use_zstacking,
'tiling': tiling,
'layer_configs': layer_configs,
'period': time_params['period'],
'duration': time_params['duration'],
'frame_dimensions': frame_dimensions,
'binning_size': get_binning_from_ui(),
}
return config
def get_auto_gain_settings() -> dict:
autogain_settings = settings['protocol']['autogain'].copy()
autogain_settings['max_duration'] = datetime.timedelta(seconds=autogain_settings['max_duration_seconds'])
del autogain_settings['max_duration_seconds']
return autogain_settings
def create_hyperstacks_if_needed():
image_capture_config = get_image_capture_config_from_ui()
if image_capture_config['output_format']['sequenced'] == 'ImageJ Hyperstack':
_, objective = get_current_objective_info()
stack_builder = StackBuilder()
stack_builder.load_folder(
path=sequenced_capture_executor.run_dir(),
tiling_configs_file_loc=pathlib.Path(source_path) / "data" / "tiling.json",
binning_size=get_binning_from_ui(),
focal_length=objective['focal_length'],
)
def get_current_objective_info() -> tuple[str, dict]:
objective_id = settings['objective_id']
objective = objective_helper.get_objective_info(objective_id=objective_id)
return objective_id, objective
def _handle_ui_update_for_axis(axis: str):
axis = axis.upper()
if axis == 'Z':
lumaview.ids['motionsettings_id'].ids['verticalcontrol_id'].update_gui()
elif axis in ('X', 'Y', 'XY'):
lumaview.ids['motionsettings_id'].update_xy_stage_control_gui()
# Wrapper function when moving to update UI position
def move_absolute_position(
axis: str,
pos: float,
wait_until_complete: bool = False,
overshoot_enabled: bool = True
):
lumaview.scope.move_absolute_position(
axis=axis,
pos=pos,
wait_until_complete=wait_until_complete,
overshoot_enabled=overshoot_enabled
)
_handle_ui_update_for_axis(axis=axis)
# Wrapper function when moving to update UI position
def move_relative_position(
axis: str,
um: float,
wait_until_complete: bool = False,
overshoot_enabled: bool = True
):
lumaview.scope.move_relative_position(
axis=axis,
um=um,
wait_until_complete=wait_until_complete,
overshoot_enabled=overshoot_enabled
)
_handle_ui_update_for_axis(axis=axis)
def move_home(axis: str):
global version
axis = axis.upper()
Window.set_title(f"Lumaview Pro {version} | Homing, please wait...")
if axis == 'Z':
lumaview.scope.zhome()
elif axis == 'XY':
lumaview.scope.xyhome()
_handle_ui_update_for_axis(axis=axis)
Clock.schedule_once(lambda dt: Window.set_title(f"Lumaview Pro {version}"), 1)
def live_histo_off():
if live_histo_setting == True and lumaview.ids['viewer_id'].ids['scope_display_id'].use_live_image_histogram_equalization == True:
lumaview.ids['viewer_id'].ids['scope_display_id'].use_live_image_histogram_equalization = False
logger.info('[LVP Main ] Live Histogram Equalization] False')
def live_histo_reverse():
if live_histo_setting == True and lumaview.ids['viewer_id'].ids['scope_display_id'].use_live_image_histogram_equalization == False:
lumaview.ids['viewer_id'].ids['scope_display_id'].use_live_image_histogram_equalization = True
logger.info('[LVP Main ] Live Histogram Equalization] True')
# -------------------------------------------------------------------------
# SCOPE DISPLAY Image representing the microscope camera
# -------------------------------------------------------------------------
class ScopeDisplay(Image):
record = BooleanProperty(None)
record = False
play = BooleanProperty(None)
play = True
def __init__(self, **kwargs):
super(ScopeDisplay,self).__init__(**kwargs)
logger.info('[LVP Main ] ScopeDisplay.__init__()')
self.use_bullseye = False
self.use_crosshairs = False
self.use_live_image_histogram_equalization = False
self._contrast_stretcher = ContrastStretcher(
window_len=3,
bottom_pct=0.3,
top_pct=0.3,
)
self.use_full_pixel_depth = False
self.start()
def start(self, fps = 10):
logger.info('[LVP Main ] ScopeDisplay.start()')
self.fps = fps
logger.info('[LVP Main ] Clock.schedule_interval(self.update, 1.0 / self.fps)')
Clock.schedule_interval(self.update_scopedisplay, 1.0 / self.fps)
def stop(self):
logger.info('[LVP Main ] ScopeDisplay.stop()')
logger.info('[LVP Main ] Clock.unschedule(self.update)')
Clock.unschedule(self.update_scopedisplay)
def touch(self, target: Widget, event: MotionEvent):
if event.is_touch and (event.device == 'mouse') and (event.button == 'right'):
norm_texture_width, norm_texture_height = self.norm_image_size
norm_texture_x_min = self.center_x - norm_texture_width/2
norm_texture_x_max = self.center_x + norm_texture_width/2
norm_texture_y_min = self.center_y - norm_texture_height/2
norm_texture_y_max = self.center_y + norm_texture_height/2
click_pos_x = event.pos[0]
click_pos_y = event.pos[1]
# Check if click occurred within texture
if (click_pos_x >= norm_texture_x_min) and (click_pos_x <= norm_texture_x_max) and \
(click_pos_y >= norm_texture_y_min) and (click_pos_y <= norm_texture_y_max):
norm_texture_click_pos_x = click_pos_x - norm_texture_x_min
norm_texture_click_pos_y = click_pos_y - norm_texture_y_min
texture_width, texture_height = self.texture_size
# Scale to image pixels
texture_click_pos_x = norm_texture_click_pos_x * texture_width / norm_texture_width
texture_click_pos_y = norm_texture_click_pos_y * texture_height / norm_texture_height
# Distance from center
x_dist_pixel = texture_click_pos_x - texture_width/2 # Positive means to the right of center
y_dist_pixel = texture_click_pos_y - texture_height/2 # Positive means above center
_, objective = get_current_objective_info()
pixel_size_um = common_utils.get_pixel_size(
focal_length=objective['focal_length'],
binning_size=get_binning_from_ui(),
)
x_dist_um = x_dist_pixel * pixel_size_um
y_dist_um = y_dist_pixel * pixel_size_um
move_relative_position(axis='X', um=x_dist_um)
move_relative_position(axis='Y', um=y_dist_um)
@staticmethod
def add_crosshairs(image):
height, width = image.shape[0], image.shape[1]
if image.ndim == 3:
is_color = True
else:
is_color = False
center_x = round(width/2)
center_y = round(height/2)
# Crosshairs - 2 pixels wide
if is_color:
image[:,center_x-1:center_x+1,:] = 255
image[center_y-1:center_y+1,:,:] = 255
else:
image[:,center_x-1:center_x+1] = 255
image[center_y-1:center_y+1,:] = 255
# Radiating circles
num_circles = 4
minimum_dimension = min(height, width)
circle_spacing = round(minimum_dimension/ 2 / num_circles)
for i in range(num_circles):
radius = (i+1) * circle_spacing
rr, cc = skimage.draw.circle_perimeter(center_y, center_x, radius=radius, shape=image.shape)
image[rr, cc] = 255
# To make circles 2 pixel wide...
rr, cc = skimage.draw.circle_perimeter(center_y, center_x, radius=radius+1, shape=image.shape)
image[rr, cc] = 255
return image
@staticmethod
def transform_to_bullseye(image):
image_bullseye = np.zeros((*image.shape, 3), dtype=np.uint8)
# The range is defined by (start_value, end_value]
# key: [start_value, end_value, RGB Value]
color_map = {
0: [ -1, 5, 0, 0, 0],
1: [ 5, 15, 0, 255, 0],
2: [ 15, 25, 0, 0, 0],
3: [ 25, 35, 0, 255, 0],
4: [ 35, 45, 0, 0, 0],
5: [ 45, 55, 0, 255, 0],
6: [ 55, 65, 0, 0, 0],
7: [ 65, 75, 0, 255, 0],
8: [ 75, 85, 0, 0, 0],
9: [ 85, 95, 0, 255, 0],
10: [ 95, 105, 0, 0, 0],
11: [105, 115, 0, 255, 0],
12: [115, 125, 0, 0, 0],
13: [125, 135, 0, 0, 255],
14: [135, 145, 0, 0, 0],
15: [145, 155, 0, 255, 0],
16: [155, 165, 0, 0, 0],
17: [165, 175, 0, 255, 0],
18: [175, 185, 0, 0, 0],
19: [185, 195, 0, 255, 0],
20: [195, 205, 0, 0, 0],
21: [205, 215, 0, 255, 0],
22: [215, 225, 0, 0, 0],
23: [225, 235, 0, 255, 0],
24: [235, 245, 0, 0, 0],
25: [245, 255, 255, 0, 0]
}
for key in color_map.keys():
start, end, *_rgb = color_map[key]
boolean_array = np.logical_and(image > start, image <= end)
image_bullseye[boolean_array] = _rgb
return image_bullseye
def update_scopedisplay(self, dt=0):
global lumaview
global debug_counter
if lumaview.scope.camera.active == False:
self.source = "./data/icons/camera to USB.png"
return
image = lumaview.scope.get_image(force_to_8bit=True)
if (image is False) or (image.size == 0):
return
if ENGINEERING_MODE == True:
debug_counter += 1
if debug_counter == 30:
debug_counter = 0
if debug_counter % 10 == 0:
mean = round(np.mean(a=image), 2)
stddev = round(np.std(a=image), 2)
af_score = lumaview.scope.focus_function(
image=image,
include_logging=False
)
open_layer = None
for layer in common_utils.get_layers():
accordion = layer + '_accordion'
if lumaview.ids['imagesettings_id'].ids[accordion].collapse == False:
open_layer = layer
break
if open_layer is not None:
lumaview.ids['imagesettings_id'].ids[open_layer].ids['image_stats_mean_id'].text = f"Mean: {mean}"
lumaview.ids['imagesettings_id'].ids[open_layer].ids['image_stats_stddev_id'].text = f"StdDev: {stddev}"
lumaview.ids['imagesettings_id'].ids[open_layer].ids['image_af_score_id'].text = f"AF Score: {af_score}"
if debug_counter % 3 == 0:
if self.use_bullseye:
image_bullseye = self.transform_to_bullseye(image=image)
if self.use_crosshairs:
image_bullseye = self.add_crosshairs(image=image_bullseye)
texture = Texture.create(size=(image_bullseye.shape[1],image_bullseye.shape[0]), colorfmt='rgb')
texture.blit_buffer(image_bullseye.tobytes(), colorfmt='rgb', bufferfmt='ubyte')
self.texture = texture
if not self.use_bullseye:
if self.use_live_image_histogram_equalization:
image = self._contrast_stretcher.update(image)
# image=cv2.normalize(src=image, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
if self.use_crosshairs:
image = self.add_crosshairs(image=image)
# Convert to texture for display (using OpenGL)
texture = Texture.create(size=(image.shape[1],image.shape[0]), colorfmt='luminance')
texture.blit_buffer(image.flatten(), colorfmt='luminance', bufferfmt='ubyte')
self.texture = texture
if self.record == True:
lumaview.live_capture()
# -------------------------------------------------------------------------
# COMPOSITE CAPTURE FloatLayout with shared capture capabilities
# -------------------------------------------------------------------------
class CompositeCapture(FloatLayout):
def __init__(self, **kwargs):
super(CompositeCapture,self).__init__(**kwargs)
# Gets the current well label (ex. A1, C2, ...)
def get_well_label(self):
_, labware = get_selected_labware()
# Get target position
try:
x_target = lumaview.scope.get_target_position('X')
y_target = lumaview.scope.get_target_position('Y')
except:
logger.exception('[LVP Main ] Error talking to Motor board.')
raise
x_target, y_target = coordinate_transformer.stage_to_plate(
labware=labware,
stage_offset=settings['stage_offset'],