forked from EtalumaSupport/LumaViewPro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlumaviewpro.py
3024 lines (2415 loc) · 118 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) 2023 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
MODIFIED:
June 24, 2023
'''
# General
import os
import numpy as np
import csv
import time
import json
import glob
from lvp_logger import logger
from plyer import filechooser
# 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
# 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.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
# User Interface
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
# Video Related
from kivy.graphics.texture import Texture
#post processing
from image_stitcher import image_stitcher
import cv2
# Hardware
from labware import WellPlate
import lumascope_api
import post_processing
global lumaview
global settings
abspath = os.path.abspath(__file__)
basename = os.path.basename(__file__)
source_path = abspath[:-len(basename)]
print(source_path)
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 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
# -------------------------------------------------------------------------
# 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.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 update_scopedisplay(self, dt=0):
global lumaview
if lumaview.scope.camera.active != False:
array = lumaview.scope.get_image()
if array is False:
return
# Convert to texture for display (using OpenGL)
texture = Texture.create(size=(array.shape[1],array.shape[0]), colorfmt='luminance')
texture.blit_buffer(array.flatten(), colorfmt='luminance', bufferfmt='ubyte')
# display image from the texture
self.texture = texture
else:
self.source = "./data/icons/camera to USB.png"
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):
current_labware = WellPlate()
current_labware.load_plate(settings['protocol']['labware'])
protocol_settings = lumaview.ids['motionsettings_id'].ids['protocol_settings_id']
# 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 = protocol_settings.stage_to_plate(x_target, y_target)
well_x, well_y = current_labware.get_well_index(x_target, y_target)
letter = chr(ord('A') + well_y)
return f'{letter}{well_x + 1}'
def live_capture(self):
print("Custom capture")
logger.info('[LVP Main ] CompositeCapture.live_capture()')
global lumaview
save_folder = settings['live_folder']
file_root = 'live_'
color = 'BF'
well_label = self.get_well_label()
append = f'{well_label}_{color}'
layers = ['BF', 'PC', 'EP', 'Blue', 'Green', 'Red']
for layer in layers:
accordion = layer + '_accordion'
if lumaview.ids['imagesettings_id'].ids[accordion].collapse == False:
if lumaview.ids['imagesettings_id'].ids[layer].ids['false_color'].active:
color = layer
# lumaview.scope.get_image()
lumaview.scope.save_live_image(save_folder, file_root, append, color)
def custom_capture(self, channel, illumination, gain, exposure, false_color = True):
print("Custom capture")
logger.info('[LVP Main ] CompositeCapture.custom_capture()')
global lumaview
global settings
# Set gain and exposure
lumaview.scope.set_gain(gain)
lumaview.scope.set_exposure_time(exposure)
# Save Settings
color = lumaview.scope.ch2color(channel)
save_folder = settings[color]['save_folder']
file_root = settings[color]['file_root']
well_label = self.get_well_label()
append = f'{well_label}_{color}'
# Illuminate
if lumaview.scope.led:
lumaview.scope.led_on(channel, illumination)
logger.info('[LVP Main ] lumaview.scope.led_on(channel, illumination)')
else:
logger.warning('LED controller not available.')
# TODO: replace sleep + get_image with scope.capture - will require waiting on capture complete
# Grab image and save
#time.sleep(2*exposure/1000+0.2)
#lumaview.scope.get_image()
lumaview.scope.capture()
if false_color:
lumaview.scope.save_live_image(save_folder, file_root, append, color)
else:
lumaview.scope.save_live_image(save_folder, file_root, append, 'BF')
# Turn off LEDs
if lumaview.scope.led:
lumaview.scope.leds_off()
logger.info('[LVP Main ] lumaview.scope.leds_off()')
else:
logger.warning('LED controller not available.')
# capture and save a composite image using the current settings
def composite_capture(self):
logger.info('[LVP Main ] CompositeCapture.composite_capture()')
global lumaview
if lumaview.scope.camera.active == False:
return
scope_display = self.ids['viewer_id'].ids['scope_display_id']
img = np.zeros((settings['frame']['height'], settings['frame']['width'], 3))
layers = ['BF', 'PC', 'EP', 'Blue', 'Green', 'Red']
for layer in layers:
if settings[layer]['acquire'] == True:
# Go to focus and wait for arrival
lumaview.ids['imagesettings_id'].ids[layer].goto_focus()
while not lumaview.scope.get_target_status('Z'):
time.sleep(.001)
# set the gain and exposure
gain = settings[layer]['gain']
lumaview.scope.set_gain(gain)
exposure = settings[layer]['exp']
lumaview.scope.set_exposure_time(exposure)
# update illumination to currently selected settings
illumination = settings[layer]['ill']
# Dark field capture
if lumaview.scope.led:
lumaview.scope.leds_off()
logger.info('[LVP Main ] lumaview.scope.leds_off()')
else:
logger.warning('LED controller not available.')
# TODO: replace sleep + get_image with scope.capture - will require waiting on capture complete
time.sleep(2*exposure/1000+0.2)
scope_display.update_scopedisplay() # Why?
darkfield = lumaview.scope.get_image()
# Florescent capture
if lumaview.scope.led:
lumaview.scope.led_on(lumaview.scope.color2ch(layer), illumination)
logger.info('[LVP Main ] lumaview.scope.led_on(lumaview.scope.color2ch(layer), illumination)')
else:
logger.warning('LED controller not available.')
# TODO: replace sleep + get_image with scope.capture - will require waiting on capture complete
time.sleep(2*exposure/1000+0.2)
exposed = lumaview.scope.get_image()
scope_display.update_scopedisplay() # Why?
corrected = exposed - np.minimum(exposed,darkfield)
# buffer the images
if layer == 'Blue':
img[:,:,0] = corrected
elif layer == 'Green':
img[:,:,1] = corrected
elif layer == 'Red':
img[:,:,2] = corrected
# # if Brightfield is included
# else:
# a = 0.3
# img[:,:,0] = img[:,:,0]*a + corrected*(1-a)
# img[:,:,1] = img[:,:,1]*a + corrected*(1-a)
# img[:,:,2] = img[:,:,2]*a + corrected*(1-a)
if lumaview.scope.led:
lumaview.scope.leds_off()
logger.info('[LVP Main ] lumaview.scope.leds_off()')
else:
logger.warning('LED controller not available.')
# turn off all LED toggle buttons and histograms
lumaview.ids['imagesettings_id'].ids[layer].ids['apply_btn'].state = 'normal'
Clock.unschedule(lumaview.ids['imagesettings_id'].ids[layer].ids['histo_id'].histogram)
logger.info('[LVP Main ] Clock.unschedule(lumaview...histogram)')
# lumaview.ids['imagesettings_id'].ids[layer].ids['apply_btn'].state = 'normal'
lumaview.ids['composite_btn'].state = 'normal'
img = np.flip(img, 0)
save_folder = settings['live_folder']
file_root = 'composite_'
# append = str(int(round(time.time() * 1000)))
well_label = self.get_well_label()
append = f'{well_label}'
# generate filename and save path string
initial_id = '_000001'
filename = file_root + append + initial_id + '.tiff'
path = save_folder + '/' + filename
# Obtain next save path if current directory already exists
while os.path.exists(path):
path = lumaview.scope.get_next_save_path(path)
cv2.imwrite(path, img.astype(np.uint8))
# -------------------------------------------------------------------------
# MAIN DISPLAY of LumaViewPro App
# -------------------------------------------------------------------------
class MainDisplay(CompositeCapture): # i.e. global lumaview
def __init__(self, **kwargs):
super(MainDisplay,self).__init__(**kwargs)
self.scope = lumascope_api.Lumascope()
def cam_toggle(self):
logger.info('[LVP Main ] MainDisplay.cam_toggle()')
scope_display = self.ids['viewer_id'].ids['scope_display_id']
if self.scope.camera.active == False:
return
if scope_display.play == True:
scope_display.play = False
if self.scope.led:
self.scope.leds_off()
logger.info('[LVP Main ] self.scope.leds_off()')
scope_display.stop()
else:
scope_display.play = True
scope_display.start()
def record(self):
logger.info('[LVP Main ] MainDisplay.record()')
scope_display = self.ids['viewer_id'].ids['scope_display_id']
if self.scope.camera.active == False:
return
scope_display.record = not scope_display.record
def fit_image(self):
logger.info('[LVP Main ] MainDisplay.fit_image()')
if self.scope.camera.active == False:
return
self.ids['viewer_id'].scale = 1
self.ids['viewer_id'].pos = (0,0)
def one2one_image(self):
logger.info('[LVP Main ] MainDisplay.one2one_image()')
if self.scope.camera.active == False:
return
w = self.width
h = self.height
scale_hor = float(lumaview.scope.get_width()) / float(w)
scale_ver = float(lumaview.scope.get_height()) / float(h)
scale = max(scale_hor, scale_ver)
self.ids['viewer_id'].scale = scale
self.ids['viewer_id'].pos = (int((w-scale*w)/2),int((h-scale*h)/2))
# -----------------------------------------------------------------------------
# Shader code
# Based on code from the kivy example Live Shader Editor found at:
# kivy.org/doc/stable/examples/gen__demo__shadereditor__main__py.html
# -----------------------------------------------------------------------------
fs_header = '''
#ifdef GL_ES
precision highp float;
#endif
/* Outputs from the vertex shader */
varying vec4 frag_color;
varying vec2 tex_coord0;
/* uniform texture samplers */
uniform sampler2D texture0;
/* fragment attributes
attribute float red_gain;
attribute float green_gain;
attribute float blue_gain; */
/* custom one */
uniform vec2 resolution;
uniform float time;
uniform vec4 black_point;
uniform vec4 white_point;
'''
vs_header = '''
#ifdef GL_ES
precision highp float;
#endif
/* Outputs to the fragment shader */
varying vec4 frag_color;
varying vec2 tex_coord0;
/* vertex attributes */
attribute vec2 vPosition;
attribute vec2 vTexCoords0;
/* uniform variables */
uniform mat4 modelview_mat;
uniform mat4 projection_mat;
uniform vec4 color;
'''
# global illumination_vals
# illumination_vals = (0., )*4
# global gain_vals
# gain_vals = (1., )*4
class ShaderViewer(Scatter):
black = ObjectProperty(0.)
white = ObjectProperty(1.)
fs = StringProperty('''
void main (void) {
gl_FragColor =
white_point *
frag_color *
texture2D(texture0, tex_coord0)
- black_point;
//gl_FragColor = pow(glFragColor.rgb, 1/gamma)
}
''')
vs = StringProperty('''
void main (void) {
frag_color = color;
tex_coord0 = vTexCoords0;
gl_Position =
projection_mat *
modelview_mat *
vec4(vPosition.xy, 0.0, 1.0);
}
''')
def __init__(self, **kwargs):
super(ShaderViewer, self).__init__(**kwargs)
logger.info('[LVP Main ] ShaderViewer.__init__()')
self.canvas = RenderContext()
self.canvas.shader.fs = fs_header + self.fs
self.canvas.shader.vs = vs_header + self.vs
self.white = 1.
self.black = 0.
def on_touch_down(self, touch):
logger.info('[LVP Main ] ShaderViewer.on_touch_down()')
# Override Scatter's `on_touch_down` behavior for mouse scroll
if touch.is_mouse_scrolling:
if touch.button == 'scrolldown':
if self.scale < 100:
self.scale = self.scale * 1.1
elif touch.button == 'scrollup':
if self.scale > 1:
self.scale = max(1, self.scale * 0.8)
# If some other kind of "touch": Fall back on Scatter's behavior
else:
super(ShaderViewer, self).on_touch_down(touch)
def update_shader(self, false_color='BF'):
# logger.info('[LVP Main ] ShaderViewer.update_shader()')
c = self.canvas
c['projection_mat'] = Window.render_context['projection_mat']
c['time'] = Clock.get_boottime()
c['resolution'] = list(map(float, self.size))
c['black_point'] = (self.black, )*4
c['gamma'] = 2.2
if false_color == 'Red':
c['white_point'] = (self.white, 0., 0., 1.)
elif false_color == 'Green':
c['white_point'] = (0., self.white, 0., 1.)
elif false_color == 'Blue':
c['white_point'] = (0., 0., self.white, 1.)
else:
c['white_point'] = (self.white, )*4
def on_fs(self, instance, value):
self.canvas.shader.fs = value
def on_vs(self, instance, value):
self.canvas.shader.vs = value
Factory.register('ShaderViewer', cls=ShaderViewer)
class MotionSettings(BoxLayout):
settings_width = dp(300)
def __init__(self, **kwargs):
super().__init__(**kwargs)
logger.info('[LVP Main ] MotionSettings.__init__()')
# Hide (and unhide) motion settings
def toggle_settings(self):
logger.info('[LVP Main ] MotionSettings.toggle_settings()')
global lumaview
scope_display = lumaview.ids['viewer_id'].ids['scope_display_id']
scope_display.stop()
self.ids['verticalcontrol_id'].update_gui()
self.ids['xy_stagecontrol_id'].update_gui()
# move position of motion control
if self.ids['toggle_motionsettings'].state == 'normal':
self.pos = -self.settings_width+30, 0
else:
self.pos = 0, 0
if scope_display.play == True:
scope_display.start()
def check_settings(self, *args):
logger.info('[LVP Main ] MotionSettings.check_settings()')
if self.ids['toggle_motionsettings'].state == 'normal':
self.pos = -self.settings_width+30, 0
else:
self.pos = 0, 0
'''
class PostProcessing(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
global settings
#stitching params (see more info in image_stitcher.py):
self.raw_images_folder = settings['live_folder'] # I'm guessing not ./capture/ because that would have frames over time already (to make video)
self.combine_colors = False #True if raw images are in separate red/green/blue channels and need to be first combined
self.ext = "tiff" #or read it from settings?
self.stitching_method = "features" # "features" - Low method, "position" - based on position information
self.stitched_save_name = "last_composite_img.tiff"
self.positions_file = None #relevant if stitching method is position, will read positions from that file
self.pos2pix = 2630 # relevant if stitching method is position. The scale conversion for pos info into pixels
self.target = []
def convert_to_avi(self):
error_log('PostProcessing.convert_to_avi()')
# # self.choose_folder()
# save_location = './capture/movie.avi'
# img_array = []
# for filename in glob.glob('./capture/*.tiff'):
# img = cv2.imread(filename)
# height, width, layers = img.shape
# size = (width,height)
# img_array.append(img)
# if len(img_array) > 0:
# out = cv2.VideoWriter(save_location,cv2.VideoWriter_fourcc(*'DIVX'), 5, size)
# for i in range(len(img_array)):
# out.write(img_array[i])
# out.release()
def stitch(self):
error_log('PostProcessing.stitch()')
self.stitched_image = image_stitcher(images_folder=self.raw_images_folder, combine_colors = self.combine_colors, ext = self.ext,
method = self.stitching_method,save_name = self.stitched_save_name,
positions_file = self.positions_file,pos2pix = self.pos2pix,post_process = False)
'''
class PostProcessingAccordion(BoxLayout):
def __init__(self, **kwargs):
#super(PostProcessingAccordion,self).__init__(**kwargs)
super().__init__(**kwargs)
#self.post = post_processing.PostProcessing()
#global settings
#stitching params (see more info in image_stitcher.py):
#self.raw_images_folder = settings['live_folder'] # I'm guessing not ./capture/ because that would have frames over time already (to make video)
self.combine_colors = False #True if raw images are in separate red/green/blue channels and need to be first combined
self.ext = "tiff" #or read it from settings?
self.stitching_method = "features" # "features" - Low method, "position" - based on position information
self.stitched_save_name = "last_composite_img.tiff"
self.positions_file = None #relevant if stitching method is position, will read positions from that file
self.pos2pix = 2630 # relevant if stitching method is position. The scale conversion for pos info into pixels
self.tiling_target = []
self.tiling_min = [120000, 80000]
self.tiling_max = [0, 0]
def convert_to_avi(self):
logger.debug('[LVP Main ] PostProcessingAccordian.convert_to_avi() not yet implemented')
#error_log('PostProcessing.convert_to_avi()')
# # self.choose_folder()
# save_location = './capture/movie.avi'
# img_array = []
# for filename in glob.glob('./capture/*.tiff'):
# img = cv2.imread(filename)
# height, width, layers = img.shape
# size = (width,height)
# img_array.append(img)
# if len(img_array) > 0:
# out = cv2.VideoWriter(save_location,cv2.VideoWriter_fourcc(*'DIVX'), 5, size)
# for i in range(len(img_array)):
# out.write(img_array[i])
# out.release()
def stitch(self):
logger.debug('[LVP Main ] PostProcessingAccordian.stitch() not fully implemented')
#error_log('PostProcessing.stitch()')
self.stitched_image = image_stitcher(images_folder=self.raw_images_folder,
combine_colors = self.combine_colors,
ext = self.ext,
method = self.stitching_method,
save_name = self.stitched_save_name,
positions_file = self.positions_file,
pos2pix = self.pos2pix,post_process = False)
def add_tiling_step(self):
logger.debug('[LVP Main ] PostProcessing.add_tiling_step() not fully implemented')
x_current = lumaview.scope.get_current_position('X')
x_current = np.clip(x_current, 0, 120000) # prevents crosshairs from leaving the stage area
y_current = lumaview.scope.get_current_position('Y')
y_current = np.clip(y_current, 0, 80000) # prevents crosshairs from leaving the stage area
new_step = [x_current,y_current]
self.tiling_target.append(new_step)
self.tiling_min = [min(x_current, self.tiling_min[0]), min(y_current, self.tiling_min[1])]
self.tiling_max = [max(x_current, self.tiling_max[0]), max(y_current, self.tiling_max[1])]
print(new_step)
print(self.tiling_min)
print(self.tiling_max)
lumaview.ids['motionsettings_id'].ids['post_processing_id'].ids['tiling_stage_id'].ROI_min = self.tiling_min
lumaview.ids['motionsettings_id'].ids['post_processing_id'].ids['tiling_stage_id'].ROI_max = self.tiling_max
print(lumaview.ids['motionsettings_id'].ids['post_processing_id'].ids['tiling_stage_id'].ROI_min)
print(lumaview.ids['motionsettings_id'].ids['post_processing_id'].ids['tiling_stage_id'].ROI_max)
return
def start_tiling(self):
logger.debug('[LVP Main ] PostProcessing.start_tiling() not yet implemented')
return
def open_folder(self):
logger.debug('[LVP Main ] PostProcessing.open_folder() not yet implemented')
class ShaderEditor(BoxLayout):
fs = StringProperty('''
void main (void){
gl_FragColor =
white_point *
frag_color *
texture2D(texture0, tex_coord0)
- black_point;
}
''')
vs = StringProperty('''
void main (void) {
frag_color = color;
tex_coord0 = vTexCoords0;
gl_Position =
projection_mat *
modelview_mat *
vec4(vPosition.xy, 0.0, 1.0);
}
''')
viewer = ObjectProperty(None)
hide_editor = ObjectProperty(None)
hide_editor = True
def __init__(self, **kwargs):
super(ShaderEditor, self).__init__(**kwargs)
logger.info('[LVP Main ] ShaderEditor.__init__()')
self.test_canvas = RenderContext()
s = self.test_canvas.shader
self.trigger_compile = Clock.create_trigger(self.compile_shaders, -1)
self.bind(fs=self.trigger_compile, vs=self.trigger_compile)
def compile_shaders(self, *largs):
logger.info('[LVP Main ] ShaderEditor.compile_shaders()')
if not self.viewer:
logger.warning('[LVP Main ] ShaderEditor.compile_shaders() Fail')
return
# we don't use str() here because it will crash with non-ascii char
fs = fs_header + self.fs
vs = vs_header + self.vs
self.viewer.fs = fs
self.viewer.vs = vs
# Hide (and unhide) Shader settings
def toggle_editor(self):
logger.info('[LVP Main ] ShaderEditor.toggle_editor()')
if self.hide_editor == False:
self.hide_editor = True
self.pos = -285, 0
else:
self.hide_editor = False
self.pos = 0, 0
class ImageSettings(BoxLayout):
settings_width = dp(300)
def __init__(self, **kwargs):
super().__init__(**kwargs)
logger.info('[LVP Main ] ImageSettings.__init__()')
# Hide (and unhide) main settings
def toggle_settings(self):
self.update_transmitted()
logger.info('[LVP Main ] ImageSettings.toggle_settings()')
global lumaview
scope_display = lumaview.ids['viewer_id'].ids['scope_display_id']
scope_display.stop()
# move position of settings and stop histogram if main settings are collapsed
if self.ids['toggle_imagesettings'].state == 'normal':
self.pos = lumaview.width - 30, 0
layers = ['BF', 'PC', 'EP', 'Blue', 'Green', 'Red']
for layer in layers:
Clock.unschedule(lumaview.ids['imagesettings_id'].ids[layer].ids['histo_id'].histogram)
logger.info('[LVP Main ] Clock.unschedule(lumaview...histogram)')
else:
self.pos = lumaview.width - self.settings_width, 0
if scope_display.play == True:
scope_display.start()
def update_transmitted(self):
layers = ['BF', 'PC', 'EP']
for layer in layers:
accordion = layer + '_accordion'
# Remove 'Colorize' option in transmitted channels control
# -----------------------------------------------------
self.ids[layer].ids['false_color_label'].text = ''
self.ids[layer].ids['false_color'].color = (0., )*4
# Adjust 'Illumination' range
self.ids[layer].ids['ill_slider'].max = 50
def accordion_collapse(self):
logger.info('[LVP Main ] ImageSettings.accordion_collapse()')
global lumaview
# turn off the camera update and all LEDs
scope_display = lumaview.ids['viewer_id'].ids['scope_display_id']
scope_display.stop()
if lumaview.scope.led:
lumaview.scope.leds_off()
logger.info('[LVP Main ] lumaview.scope.leds_off()')
else:
logger.warning('LED controller not available.')
# turn off all LED toggle buttons and histograms
layers = ['BF', 'PC', 'EP', 'Blue', 'Green', 'Red']
for layer in layers:
lumaview.ids['imagesettings_id'].ids[layer].ids['apply_btn'].state = 'normal'
Clock.unschedule(lumaview.ids['imagesettings_id'].ids[layer].ids['histo_id'].histogram)
logger.info('[LVP Main ] Clock.unschedule(lumaview...histogram)')
accordion = layer + '_accordion'
if lumaview.ids['imagesettings_id'].ids[accordion].collapse == False:
if lumaview.ids['imagesettings_id'].ids[layer].ids['false_color'].active:
lumaview.ids['viewer_id'].update_shader(false_color=layer)
else:
lumaview.ids['viewer_id'].update_shader(false_color='BF')
# Restart camera feed
if scope_display.play == True:
scope_display.start()
def check_settings(self, *args):
logger.info('[LVP Main ] ImageSettings.check_settings()')
global lumaview
if self.ids['toggle_imagesettings'].state == 'normal':
self.pos = lumaview.width - 30, 0
else:
self.pos = lumaview.width - self.settings_width, 0
class Histogram(Widget):
bg_color = ObjectProperty(None)
layer = ObjectProperty(None)
def __init__(self, **kwargs):
super(Histogram, self).__init__(**kwargs)
logger.info('[LVP Main ] Histogram.__init__()')
if self.bg_color is None:
self.bg_color = (1, 1, 1, 1)
self.hist_range_set = False
self.edges = [0,255]
self.stablize = 0.3
def histogram(self, *args):
# logger.info('[LVP Main ] Histogram.histogram()')
global lumaview
bins = 128
if lumaview.scope.camera != False:
#image = lumaview.scope.get_image()
image = lumaview.scope.image_buffer
hist = np.histogram(image, bins=bins,range=(0,256))
'''
if self.hist_range_set:
edges = self.edges
else:
edges = np.histogram_bin_edges(image, bins=1)
edges[0] = self.stablize*self.edges[0] + (1 - self.stablize)*edges[0]
edges[1] = self.stablize*self.edges[1] + (1 - self.stablize)*edges[1]
'''
# mean = np.mean(hist[1],hist[0])
lumaview.ids['viewer_id'].black = 0.0 # float(edges[0])/255.
lumaview.ids['viewer_id'].white = 1.0 # float(edges[1])/255.
# UPDATE SHADER
self.canvas.clear()
r, b, g, a = self.bg_color
self.hist = hist
#self.edges = edges
with self.canvas:
x = self.x
y = self.y
w = self.width
h = self.height
#Color(r, b, g, a/12)
#Rectangle(pos=(x, y), size=(256, h))
#Color(r, b, g, a/4)
#Rectangle(pos=(x + edges[0], y), size=(edges[1]-edges[0], h))
Color(r, b, g, a/2)
#self.color = Color(rgba=self.color)
logHistogram = lumaview.ids['imagesettings_id'].ids[self.layer].ids['logHistogram_id'].active
if logHistogram:
maxheight = np.log(np.max(hist[0])+1)
else:
maxheight = np.max(hist[0])
if maxheight > 0:
scale=h/maxheight
for i in range(len(hist[0])):
if logHistogram:
counts = scale*np.log(hist[0][i] + 1)
else:
counts = np.ceil(scale*hist[0][i])
self.pos = self.pos
Rectangle(pos=(x+max(i*512/bins-1, 1), y), size=(512/bins, counts))
#self.line = Line(points=(x+i, y, x+i, y+counts), width=1)
class VerticalControl(BoxLayout):
def __init__(self, **kwargs):
super(VerticalControl, self).__init__(**kwargs)
logger.info('[LVP Main ] VerticalControl.__init__()')
# boolean describing whether the scope is currently in the process of autofocus
self.is_autofocus = False
self.is_complete = False
def update_gui(self):
logger.info('[LVP Main ] VerticalControl.update_gui()')
try:
set_pos = lumaview.scope.get_target_position('Z') # Get target value
except:
logger.warning('[LVP Main ] Error talking to Motor board.')
self.ids['obj_position'].value = max(0, set_pos)
self.ids['z_position_id'].text = format(max(0, set_pos), '.2f')
def coarse_up(self):
logger.info('[LVP Main ] VerticalControl.coarse_up()')
coarse = settings['objective']['z_coarse']
lumaview.scope.move_relative_position('Z', coarse) # Move UP
self.update_gui()
def fine_up(self):
logger.info('[LVP Main ] VerticalControl.fine_up()')
fine = settings['objective']['z_fine']
lumaview.scope.move_relative_position('Z', fine) # Move UP
self.update_gui()
def fine_down(self):
logger.info('[LVP Main ] VerticalControl.fine_down()')
fine = settings['objective']['z_fine']
lumaview.scope.move_relative_position('Z', -fine) # Move DOWN
self.update_gui()
def coarse_down(self):
logger.info('[LVP Main ] VerticalControl.coarse_down()')
coarse = settings['objective']['z_coarse']
lumaview.scope.move_relative_position('Z', -coarse) # Move DOWN
self.update_gui()
def set_position(self, pos):
logger.info('[LVP Main ] VerticalControl.set_position()')
lumaview.scope.move_absolute_position('Z', float(pos))
self.update_gui()
def set_bookmark(self):
logger.info('[LVP Main ] VerticalControl.set_bookmark()')
height = lumaview.scope.get_current_position('Z') # Get current z height in um
settings['bookmark']['z'] = height
def set_all_bookmarks(self):
logger.info('[LVP Main ] VerticalControl.set_all_bookmarks()')
height = lumaview.scope.get_current_position('Z') # Get current z height in um
settings['bookmark']['z'] = height
settings['BF']['focus'] = height
settings['PC']['focus'] = height
settings['EP']['focus'] = height
settings['Blue']['focus'] = height
settings['Green']['focus'] = height
settings['Red']['focus'] = height
def goto_bookmark(self):
logger.info('[LVP Main ] VerticalControl.goto_bookmark()')
pos = settings['bookmark']['z']
lumaview.scope.move_absolute_position('Z', pos)
self.update_gui()
def home(self):
logger.info('[LVP Main ] VerticalControl.home()')
lumaview.scope.zhome()
self.update_gui()
# User selected the autofocus function
def autofocus(self):
logger.info('[LVP Main ] VerticalControl.autofocus()')
global lumaview
self.is_autofocus = True
self.is_complete = False
if lumaview.scope.camera.active == False: