-
Notifications
You must be signed in to change notification settings - Fork 2
/
PyPOLAR.py
2051 lines (1902 loc) · 126 KB
/
PyPOLAR.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 customtkinter as CTk
from tkinter import Event as tkEvent
from tkinter import filedialog as fd
import sys
from pathlib import Path
import joblib
import pickle
import copy
import webbrowser
import numpy as np
from scipy.signal import convolve2d, savgol_filter
from scipy.interpolate import interpn
from scipy.ndimage import rotate
from scipy.io import savemat, loadmat
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.patches import Polygon
from matplotlib.collections import PolyCollection
from matplotlib.backend_bases import FigureCanvasBase, _Mode, MouseEvent
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.backends.backend_pdf
from mpl_toolkits.axes_grid1 import make_axes_locatable
from colorcet import m_colorwheel
from PIL import Image
import cv2
from skimage.measure import manders_coloc_coeff, pearson_corr_coeff
import openpyxl
from itertools import permutations, chain
from datetime import date
import copy
from typing import List, Tuple, Union
from pypolar_classes import Stack, DataStack, Variable, ROI, Calibration, PyPOLARfigure, ROIManager, TabView, ToolTip
from pypolar_classes import Button, CheckBox, Entry, DropDown, Label, OptionMenu, SpinBox, ShowInfo, TextBox
from pypolar_classes import adjust, angle_edge, circularmean, divide_ext, find_matches, wrapto180
from pypolar_classes import button_size, geometry_info
from generate_json import font_macosx, font_windows, orange, gray, red, green, blue, text_color
try:
from ctypes import windll
myappid = 'fr.cnrs.fresnel.pypolar'
windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
pass
mpl.use('tkagg')
CTk.set_default_color_theme(Path(__file__).parent / 'polarimetry.json')
CTk.set_appearance_mode('dark')
plt.rcParams['font.size'] = 16
if sys.platform == 'darwin':
plt.rcParams['font.family'] = font_macosx
#mpl.use('macosx')
elif sys.platform == 'win32':
plt.rcParams['font.family'] = font_windows
plt.rcParams['image.origin'] = 'upper'
plt.rcParams['figure.max_open_warning'] = 100
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['savefig.bbox'] = 'tight'
plt.rcParams['savefig.dpi'] = 100
plt.ion()
def main():
app = Polarimetry()
app.mainloop()
class Polarimetry(CTk.CTk):
__version__ = '2.6.4'
dict_versions = {'2.1': 'December 5, 2022', '2.2': 'January 22, 2023', '2.3': 'January 28, 2023', '2.4': 'February 2, 2023', '2.4.1': 'February 25, 2023', '2.4.2': 'March 2, 2023', '2.4.3': 'March 13, 2023', '2.4.4': 'March 29, 2023', '2.4.5': 'May 10, 2023', '2.5': 'May 23, 2023', '2.5.3': 'October 11, 2023', '2.6': 'October 16, 2023', '2.6.2': 'April 4, 2024', '2.6.3': 'July 18, 2024', '2.6.4': 'October 21, 2024'}
__version_date__ = dict_versions.get(__version__, date.today().strftime('%B %d, %Y'))
ratio_app = 3 / 4
ratio_fig = 3 / 5
left_width = 205
figsize = (450, 450)
length_slider = 150
url_github = 'https://github.com/cchandre/Polarimetry'
url_wiki = url_github + '/wiki'
url_fresnel = 'https://www.fresnel.fr/polarimetry'
email = 'cristel.chandre@cnrs.fr'
def __init__(self) -> None:
super().__init__()
## MAIN
base_dir = Path(__file__).parent
image_path = base_dir / 'icons'
height = int(self.ratio_app * self.winfo_screenheight())
width = height + self.left_width
delx, dely = self.winfo_screenwidth() // 10, self.winfo_screenheight() // 10
dpi = self.winfo_fpixels('1i')
self.figsize = (type(self).figsize[0] / dpi, type(self).figsize[1] / dpi)
self.title('PyPOLAR')
self.geometry(f'{width}x{height}+{delx}+{dely}')
self.protocol('WM_DELETE_WINDOW', self.on_closing)
self.bind('<Command-q>', self.on_closing)
self.bind('<Command-w>', self.on_closing)
self.createcommand('tk::mac::Quit', self.on_closing)
self.configure(fg_color=gray[0])
self.icons = {file.stem: CTk.CTkImage(dark_image=Image.open(file).resize((60, 60)), size=(30, 30)) for file in image_path.glob('*.png')}
if sys.platform == 'win32':
self.iconbitmap(str(base_dir / 'main_icon.ico'))
import winreg
EXTS = ['.pyroi', '.pyreg', '.pyfig']
TYPES = ['PyPOLAR ROI', 'PyPOLAR Registration', 'PyPOLAR Figure']
ICONS = ['pyroi.ico', 'pyreg.ico', 'pyfig.ico']
try:
for EXT, TYPE, ICON in zip(EXTS, TYPES, ICONS):
key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, EXT)
winreg.SetValue(key, None, winreg.REG_SZ, TYPE)
iconkey = winreg.CreateKey(key, 'DefaultIcon')
winreg.SetValue(iconkey, None, winreg.REG_SZ, str(image_path / ICON))
winreg.CloseKey(iconkey)
winreg.CloseKey(key)
except WindowsError:
pass
## DEFINE FRAMES
left_frame = CTk.CTkScrollableFrame(master=self, corner_radius=0, fg_color=gray[0], scrollbar_button_color=gray[0], scrollbar_button_hover_color=gray[0])
left_frame.pack(side=CTk.LEFT, fill=CTk.Y, expand=False)
right_frame = CTk.CTkFrame(master=self, corner_radius=0, fg_color=gray[1])
right_frame.pack(side=CTk.RIGHT, fill=CTk.BOTH, expand=True)
self.tabview = TabView(right_frame)
## LEFT FRAME
dict_left_frame = {'column': 0, 'padx': 20, 'pady': 20}
Button(left_frame, text=' PyPOLAR', image=self.icons['blur_circular'], command=self.on_click_tab, tooltip=' - select a polarimetry method\n - download a .tiff stack file, a folder, or a PyPOLAR figure (.pyfig)\n - for a .tiff file or folder, select an option of analysis\n - select one or several regions of interest (ROI)\n - click on Analysis', hover=False, fg_color='transparent', font=CTk.CTkFont(size=24)).grid(row=0, column=0, padx=20, pady=(10, 40))
self.method = CTk.StringVar()
DropDown(left_frame, values=['1PF', 'CARS', 'SRS', 'SHG', '2PF', '4POLAR 2D', '4POLAR 3D'], image=self.icons['microscope'], command=self.method_dropdown_callback, variable=self.method, tooltip=' - 1PF: one-photon fluorescence\n - CARS: coherent anti-Stokes Raman scattering\n - SRS: stimulated Raman scattering\n - SHG: second-harmonic generation\n - 2PF: two-photon fluorescence\n - 4POLAR 2D: 2D 4POLAR fluorescence (not yet implemented)\n - 4POLAR 3D: 3D 4POLAR fluorescence').grid(row=1, **dict_left_frame)
self.openfile_dropdown_value = CTk.StringVar()
self.openfile_dropdown = DropDown(left_frame, values=['Open file', 'Open folder', 'Open figure'], image=self.icons['download_file'], variable=self.openfile_dropdown_value, command=self.open_file_callback, tooltip=' - open a file (.tif or .tiff stack file)\n - open a folder containing .tif or .tiff stack files\n - open figure (.pyfig file saved from a previous analysis)')
self.openfile_dropdown.grid(row=2, **dict_left_frame)
self.option = CTk.StringVar()
self.options_dropdown = DropDown(left_frame, values=['Thresholding (manual)', 'Mask (manual)'], image=self.icons['build'], variable=self.option, state='disabled', command=self.options_dropdown_callback, tooltip=' select the method of analysis\n - intensity thresholding or segmentation mask for single file analysis (manual) or batch processing (auto)\n - the mask has to be binary and in PNG format and have the same file name as the respective polarimetry data file')
self.options_dropdown.grid(row=3, **dict_left_frame)
self.add_roi_button = Button(left_frame, text='Add ROI', image=self.icons['roi'], command=self.add_roi_callback, tooltip=' add a region of interest: polygon (left button), freeform (right button); double-click to close the ROI')
self.add_roi_button.grid(row=4, **dict_left_frame)
self.analysis_button = Button(left_frame, text='Analysis', command=self.analysis_callback, image=self.icons['play'], fg_color=green[0], hover_color=green[1], tooltip=' perform polarimetry analysis')
self.analysis_button.grid(row=5, **dict_left_frame)
Button(left_frame, text='Close figures', command=lambda:plt.close('all'), image=self.icons['close'], fg_color=red[0], hover_color=red[1], tooltip=' close all open figures').grid(row=6, **dict_left_frame)
## RIGHT FRAME: INTENSITY
banner = CTk.CTkFrame(master=self.tabview.tab('Intensity'), fg_color='transparent')
banner.pack(side=CTk.RIGHT, fill=CTk.Y, expand=False)
Button(banner, image=self.icons['contrast'], command=self.contrast_intensity_button_callback, tooltip=' adjust contrast\n - the chosen contrast will be the one used\n for the intensity images in figures\n - the contrast changes the intensity value displayed in the navigation toolbar\n - the chosen contrast does not affect the analysis').grid(row=0, column=0, padx=10, pady=(20, 0))
self.contrast_intensity_slider = CTk.CTkSlider(master=banner, from_=0, to=1, orientation='vertical', height=self.length_slider, command=self.contrast_intensity_slider_callback)
self.contrast_intensity_slider.set(1)
self.contrast_intensity_slider.grid(row=1, column=0, padx=10, pady=(0, 20))
self.compute_angle_button = Button(banner, image=self.icons['square'], command=self.compute_angle, tooltip=' left click to trace a line segment\n and determine its length and angle')
self.compute_angle_button.grid(row=2, column=0, padx=10, pady=20)
self.pixel_size = CTk.StringVar(value='0')
entry = CTk.CTkEntry(banner, textvariable=self.pixel_size, border_color=gray[0], width=50, justify='center')
ToolTip(entry, text=' enter the pixel size in nm')
entry.grid(row=3, column=0, padx=10, pady=0)
intensity_fig = Figure(figsize=(self.ratio_fig / dpi, self.ratio_fig / dpi), facecolor=gray[1])
self.intensity_axis = intensity_fig.add_axes([0, 0, 1, 1])
self.intensity_axis.set_axis_off()
background = plt.imread(image_path / 'blur_circular-512.png')
self.intensity_axis.imshow(background, cmap='gray', interpolation='bicubic', alpha=0.1)
self.intensity_pyfig = PyPOLARfigure(intensity_fig, master=self.tabview.tab('Intensity'))
bottomframe = CTk.CTkFrame(master=self.tabview.tab('Intensity'), fg_color='transparent')
bottomframe.pack(side=CTk.BOTTOM, fill=CTk.X, expand=False, pady=5)
self.filename_label = TextBox(master=bottomframe, width=200, height=50, tooltip=' name of file currently analyzed')
self.filename_label.pack(side=CTk.LEFT, padx=(30, 0))
sliderframe = CTk.CTkFrame(master=bottomframe, fg_color='transparent')
sliderframe.pack(side=CTk.RIGHT)
self.stack_slider = CTk.CTkSlider(master=sliderframe, from_=0, to=18, number_of_steps=18, width=self.length_slider, command=self.stack_slider_callback, state='disabled')
self.stack_slider.set(0)
self.stack_slider.pack(side=CTk.TOP)
self.stack_slider_label = Label(master=sliderframe, text='T', tooltip=' slider at T for the total intensity, otherwise scroll through the images of the stack')
self.stack_slider_label.pack(side=CTk.LEFT)
Label(master=sliderframe, fg_color='transparent', text='Stack', tooltip=' slider at T for the total intensity, otherwise scroll through the images of the stack').pack(side=CTk.RIGHT)
## RIGHT FRAME: THRSH
banner = CTk.CTkFrame(master=self.tabview.tab('Thresholding/Mask'), fg_color='transparent')
banner.pack(side=CTk.RIGHT, fill=CTk.Y, expand=False)
Button(banner, image=self.icons['contrast'], command=self.contrast_thrsh_button_callback, tooltip=' adjust contrast\n - the contrast changes the intensity value displayed in the navigation toolbar\n - the chosen contrast does not affect the analysis').grid(row=0, column=0, padx=10, pady=(20, 0))
self.contrast_thrsh_slider = CTk.CTkSlider(master=banner, from_=0, to=1, orientation='vertical', height=self.length_slider, command=self.contrast_thrsh_slider_callback)
self.contrast_thrsh_slider.set(1)
self.contrast_thrsh_slider.grid(row=1, column=0, padx=10, pady=(0, 20))
Button(banner, image=self.icons['colorize'], command=self.change_colormap, tooltip=" change the colormap used for thresholding ('hot' or 'gray')").grid(row=2, column=0, padx=10, pady=10)
self.no_background_button = Button(banner, image=self.icons['photo_fill'], command=self.no_background, tooltip=' change background to enhance visibility')
self.no_background_button.grid(row=3, column=0, padx=10, pady=10)
Button(banner, image=self.icons['open_in_new'], command=self.export_mask, tooltip=' export mask as .png').grid(row=4, column=0, padx=10, pady=10)
Button(banner, image=self.icons['format_list'], command=self.roimanager_callback, tooltip=' open ROI Manager').grid(row=5, column=0, padx=10, pady=10)
self.edge_button = Button(banner, image=self.icons['multiline_chart'], command=self.edge_button_callback, tooltip=' determine the edges of the thresholded image and compute orientations with respect to the edges')
self.edge_button.grid(row=6, column=0, padx=10, pady=10)
self.thrsh_axis_facecolor = gray[1]
self.thrsh_fig = Figure(figsize=(self.ratio_fig / dpi, self.ratio_fig / dpi), facecolor=self.thrsh_axis_facecolor)
self.thrsh_axis = self.thrsh_fig.add_axes([0, 0, 1, 1])
self.thrsh_axis.set_axis_off()
self.thrsh_axis.set_facecolor(self.thrsh_axis_facecolor)
self.thrsh_axis.imshow(background, cmap='gray', interpolation='bicubic', alpha=0.1)
self.thrsh_pyfig = PyPOLARfigure(self.thrsh_fig, master=self.tabview.tab('Thresholding/Mask'))
bottomframe = CTk.CTkFrame(master=self.tabview.tab('Thresholding/Mask'), fg_color='transparent')
bottomframe.pack(side=CTk.BOTTOM, fill=CTk.X, expand=False, pady=5)
ilow_frame = CTk.CTkFrame(master=bottomframe, fg_color='transparent')
ilow_frame.pack(side=CTk.LEFT, padx=(30, 0))
self.ilow = CTk.StringVar(value='0')
self.ilow_slider = CTk.CTkSlider(master=ilow_frame, from_=0, to=1, width=self.length_slider, command=self.ilow_slider_callback)
self.ilow_slider.set(0)
self.ilow_slider.grid(row=0, column=0, columnspan=2, sticky="sw")
Label(master=ilow_frame, text='Ilow\n', anchor='w', tooltip= ' intensity value used for thresholding\n - use the slider or enter the value manually').grid(row=1, column=0, padx=20, sticky="sw")
entry = CTk.CTkEntry(master=ilow_frame, textvariable=self.ilow, border_color=gray[1], width=100, justify=CTk.LEFT)
entry.bind('<Return>', command=self.ilow2slider_callback)
entry.grid(row=1, column=1, sticky="se")
transparency_frame = CTk.CTkFrame(master=bottomframe, fg_color='transparent')
transparency_frame.pack(side=CTk.RIGHT, padx=0)
self.transparency_slider = CTk.CTkSlider(master=transparency_frame, from_=0, to=1, width=self.length_slider, command=self.transparency_slider_callback)
self.transparency_slider.set(0)
self.transparency_slider.grid(row=0, column=0)
Label(master=transparency_frame, text='Transparency\n', tooltip=' use slider to adjust the transparency of the background image').grid(row=1, column=0, padx=20, sticky="sw")
## RIGHT FRAME: OPTIONS
left_color = left_frame.cget('fg_color')
dict_frame = {'fg_color': left_color}
scrollable_frame = CTk.CTkScrollableFrame(master=self.tabview.tab('Options'), fg_color='transparent', scrollbar_fg_color='transparent', scrollbar_button_color=right_frame.cget('fg_color'), scrollbar_button_hover_color=left_color)
scrollable_frame.columnconfigure((0, 1), weight=1)
scrollable_frame.pack(side=CTk.LEFT, fill=CTk.BOTH, expand=True)
show_save = CTk.CTkFrame(master=scrollable_frame, **dict_frame)
show_save.grid(row=0, column=0, padx=0, pady=0)
show_save.columnconfigure(0, weight=1)
Label(master=show_save, text='Figures\n', width=250, font=CTk.CTkFont(size=16)).grid(row=0, column=0, columnspan=3, padx=20, pady=(10, 0), sticky="n")
Label(master=show_save, text='Show', width=30, anchor='w').grid(row=1, column=1, padx=(10, 20), pady=0, sticky="n")
Label(master=show_save, text='Save', width=30, anchor='w').grid(row=1, column=2, padx=(0, 50), pady=0, sticky="n")
labels = ['Composite', 'Sticks', 'Histogram', 'Intensity']
self.show_table = [CheckBox(show_save) for _ in range(len(labels))]
self.save_table = [CheckBox(show_save) for _ in range(len(labels))]
for _ in range(len(labels)-1):
Label(master=show_save, text=labels[_], anchor='w', width=80, height=30).grid(row=_+2, column=0, padx=(30, 0), sticky="n")
self.save_table[_].configure(command=self.click_save_output)
self.show_table[_].grid(row=_+2, column=1, pady=0, padx=(0, 10), sticky='n')
self.save_table[_].grid(row=_+2, column=2, pady=0, padx=(0, 50), sticky='n')
Label(master=show_save, text=labels[-1], anchor='w', width=80, height=30).grid(row=len(labels)+2, column=0, padx=(30, 0), pady=(0, 10), sticky="n")
self.save_table[_].configure(command=self.click_save_output)
self.show_table[-1].grid(row=len(labels)+2, column=1, pady=(0, 10), padx=(0, 10), sticky='n')
self.save_table[-1].grid(row=len(labels)+2, column=2, pady=(0, 10), padx=(0, 50), sticky='n')
preferences = CTk.CTkFrame(master=scrollable_frame, **dict_frame)
preferences.grid(row=1, column=0, rowspan=3, padx=0, pady=(20, 0), sticky="n")
Label(master=preferences, text='Preferences\n', width=250, font=CTk.CTkFont(size=16)).grid(row=0, column=0, columnspan=2, padx=20, pady=(10, 0), sticky='n')
self.add_axes_checkbox = CheckBox(preferences, text='\nAxes on figures\n', command=self.add_axes_on_all_figures)
self.add_axes_checkbox.select()
self.add_axes_checkbox.grid(row=1, column=0, columnspan=2, padx=40, pady=0, sticky='ew')
self.colorbar_checkbox = CheckBox(preferences, text='\nColorbar on figures\n', command=self.colorbar_on_all_figures)
self.colorbar_checkbox.select()
self.colorbar_checkbox.grid(row=2, column=0, columnspan=2, padx=40, pady=0, sticky='ew')
self.colorblind_checkbox = CheckBox(preferences, text='\nColorblind-friendly\n', command=self.colorblind_on_all_figures)
self.colorblind_checkbox.grid(row=3, column=0, columnspan=2, padx=40, pady=(0, 10), sticky='ew')
labels = [' pixels per stick (horizontal)', ' pixels per stick (vertical)']
self.pixelsperstick_spinboxes = [SpinBox(master=preferences, command=self.pixelsperstick_spinbox_callback) for it in range(2)]
for _ in range(2):
self.pixelsperstick_spinboxes[_].grid(row=_+4, column=0, padx=(20, 0), pady=10)
Label(master=preferences, text=labels[_], anchor='w', tooltip=' controls the density of sticks to be plotted').grid(row=_+4, column=1, padx=(0, 20), pady=10, sticky='w')
self.histo_nbins = CTk.StringVar(value='60')
SpinBox(master=preferences, from_=10, to_=90, step_size=10, textvariable=self.histo_nbins).grid(row=6, column=0, padx=(20, 0), pady=10)
Label(master=preferences, text=' bins for histograms', anchor='w', tooltip=' controls the number of bins used in histograms').grid(row=6, column=1, padx=(0, 20), pady=10, sticky='w')
Button(preferences, image=self.icons['crop'], command=self.crop_figures_callback, tooltip=' click button to define region and crop figures').grid(row=7, column=0, columnspan=2, pady=(0, 10))
self.variable_table_frame = CTk.CTkFrame(master=scrollable_frame, **dict_frame)
self.variable_table_frame.grid(row=0, column=1, padx=0, pady=0, sticky="n")
banner = CTk.CTkFrame(master=scrollable_frame, fg_color=gray[1])
banner.grid(row=1, column=1, padx=40, pady=(10, 0), sticky="n")
Button(banner, image=self.icons['query_stats'], command=self.show_individual_fit_callback, tooltip=' show an individual fit\n - zoom into the region of interest in the Rho composite\n - click this button\n - select a pixel with the crosshair on the Rho composite then click').grid(row=0, column=0, padx=(0, 20), pady=0)
Button(banner, image=self.icons['merge'], command=self.merge_histos, tooltip=' concatenate histograms\n - choose variables in the Variables table\n - click button to select the folder containing the .mat files').grid(row=0, column=1, padx=20, pady=0)
self.per_roi = CheckBox(banner, text='per ROI', command=self.per_roi_callback, border_color=gray[0], tooltip=' show and save data/figures separately for each region of interest')
self.per_roi.grid(row=0, column=2, padx=20, pady=0)
save_ext = CTk.CTkFrame(master=scrollable_frame, **dict_frame)
Label(master=save_ext, text='Save output\n', width=250, font=CTk.CTkFont(size=16)).grid(row=0, column=0, columnspan=2, padx=(20, 20), pady=(10, 0), sticky="n")
save_ext.grid(row=2, column=1, padx=0, pady=(10, 0), sticky="n")
Label(save_ext, text='Figures', anchor='w').grid(row=1, column=0, padx=(40, 0), sticky='w')
self.figure_extension = CTk.StringVar(value='.pdf')
self.figure_extension_optionmenu = OptionMenu(save_ext, width=60, height=20, variable=self.figure_extension, values=['.pdf', '.png', '.jpeg', '.tif', '.pyfig'], state='disabled', fg_color=gray[0], button_color=gray[0], text_color_disabled=gray[1], button_hover_color=gray[0], anchor='e', tooltip=' select the file type for the saved figures')
self.figure_extension_optionmenu.grid(row=1, column=1, padx=(0, 10))
labels = ['Data (.mat)', 'Mean values (.xlsx)', 'Movie (.gif)']
self.extension_table = [CheckBox(save_ext) for _ in range(len(labels))]
for _ in range(len(labels)-1):
Label(master=save_ext, text=labels[_], anchor='w').grid(row=_+2, column=0, padx=(40, 0), sticky='w')
self.extension_table[_].grid(row=_+2, column=1, pady=0, padx=0)
Label(master=save_ext, text=labels[-1], anchor='w').grid(row=len(labels)+1, column=0, padx=(40, 0), pady=(0, 10), sticky='w')
self.extension_table[len(labels)-1].grid(row=len(labels)+1, column=1, pady=(0, 10), padx=0)
Button(scrollable_frame, image=self.icons['palette'], command=lambda:self.openweb('https://colab.research.google.com/drive/1Ho8kU1yYrtltQ0xPs5SB9osiB2fRG4SJ?usp=sharing'), tooltip=' opens the Jupyter Notebook to visualize and customize the colorbars used in PyPOLAR').grid(row=3, column=1, padx=(100, 0), pady=(10, 0), sticky="nw")
Button(scrollable_frame, image=self.icons['delete_forever'], command=self.initialize_tables, tooltip=' reinitialize Figures, Save output and Variables tables').grid(row=3, column=1, padx=(0, 100), pady=(10, 0), sticky="ne")
## RIGHT FRAME: ADV
scrollable_frame = CTk.CTkScrollableFrame(master=self.tabview.tab('Advanced'), fg_color='transparent', scrollbar_fg_color='transparent', scrollbar_button_color=right_frame.cget('fg_color'), scrollbar_button_hover_color=left_color)
scrollable_frame.columnconfigure((0, 1), weight=1)
scrollable_frame.pack(side=CTk.LEFT, fill=CTk.BOTH, expand=True)
scrollable_frame.columnconfigure((0, 1, 2), weight=1)
adv_elts = ['Dark', 'Binning', 'Polarization', 'Rotation', 'Disk cone / Calibration data', 'Intensity removal']
adv_loc = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
columnspan = [1, 2, 1, 2, 1, 2]
adv = {}
for loc, elt, cspan in zip(adv_loc, adv_elts, columnspan):
adv.update({elt: CTk.CTkFrame(master=scrollable_frame, **dict_frame)})
adv[elt].grid(row=loc[0], column=loc[1], padx=20, pady=(0, 20), sticky="n")
Label(master=adv[elt], text=elt + '\n', width=230, font=CTk.CTkFont(size=16)).grid(row=0, column=0, columnspan=cspan, padx=20, pady=(10, 0), sticky="n")
self.dark_switch = CTk.CTkSwitch(master=adv['Dark'], text='', command=self.dark_switch_callback, onvalue='on', offvalue='off', width=50)
self.dark_switch.grid(row=0, column=0, padx=20, pady=10, sticky='ne')
self.dark = CTk.StringVar()
self.dark_entry = Entry(adv['Dark'], text='Used dark value', textvariable=self.dark, row=1, column=0, sticky="nw", padx=40, tooltip=' for 1PF, use a dark value greater than 480\n - raw images correspond to a dark value 0')
self.dark_entry.bind('<Return>', command=self.intensity_callback)
self.dark_entry.set_state('disabled')
self.calculated_dark_label = Label(master=adv['Dark'], text='Calculated dark value = 0')
self.calculated_dark_label.grid(row=2, column=0, sticky='w', padx=40, pady=(0, 10))
self.offset_angle_switch = CTk.CTkSwitch(master=adv['Polarization'], text='', command=self.offset_angle_switch_callback, onvalue='on', offvalue='off', width=50)
self.offset_angle_switch.grid(row=0, column=0, padx=20, pady=10, sticky='ne')
self.offset_angle = CTk.StringVar(value='0')
self.offset_angle_entry = Entry(adv['Polarization'], text='\nOffset angle (deg)\n', textvariable=self.offset_angle, row=1, sticky="nw", padx=40)
self.offset_angle_entry.set_state('disabled')
Label(master=adv['Polarization'], text=' ').grid(row=2, column=0)
self.polar_dir = CTk.StringVar(value='clockwise')
self.polarization_button = Button(adv['Polarization'], image=self.icons[self.polar_dir.get()], command=self.change_polarization_direction, tooltip=' change polarization direction')
self.polarization_button.grid(row=2, column=0, pady=(0, 10))
Button(adv['Disk cone / Calibration data'], image=self.icons['photo'], command=self.diskcone_display, tooltip=' display the selected disk cone (for 1PF)').grid(row=1, column=0, padx=(52, 0), pady=10, sticky='w')
self.calib_dropdown = OptionMenu(master=adv['Disk cone / Calibration data'], values='', width=button_size[0]-button_size[1], height=button_size[1], dynamic_resizing=False, command=self.calib_dropdown_callback, tooltip=' 1PF: select disk cone depending on wavelength and acquisition date\n 4POLAR: select .mat file containing the calibration data')
self.calib_dropdown.grid(row=1, column=0, padx=(0, 52), pady=10, sticky='e')
self.calib_textbox = TextBox(master=adv['Disk cone / Calibration data'], width=250, height=50, state='disabled', fg_color=gray[0])
self.calib_textbox.grid(row=3, column=0, pady=10)
self.polar_dropdown = OptionMenu(master=adv['Disk cone / Calibration data'], width=button_size[0], height=button_size[1], dynamic_resizing=False, command=self.polar_dropdown_callback, state='disabled', text_color_disabled=gray[0], tooltip=' 4POLAR: select the distribution of polarizations (0,45,90,135) among quadrants clockwise\n Upper Left (UL), Upper Right (UR), Lower Right (LR), Lower Left (LL)')
angles = [0, 45, 90, 135]
self.dict_polar = {}
for p in list(permutations([0, 1, 2, 3])):
a = [angles[_] for _ in p]
self.dict_polar.update({f'UL{a[0]}-UR{a[1]}-LR{a[2]}-LL{a[3]}': p})
self.polar_dropdown.configure(values=list(self.dict_polar.keys()))
self.polar_dropdown.grid(row=4, column=0, pady=10)
labels = ['Bin width', 'Bin height']
self.bin_spinboxes = [SpinBox(adv['Binning'], command=lambda:self.intensity_callback(event=1)) for _ in range(2)]
for _ in range(2):
self.bin_spinboxes[_].bind('<Return>', command=self.intensity_callback)
self.bin_spinboxes[_].grid(row=_+1, column=0, padx=(30, 10), pady=0, sticky='e')
Label(master=adv['Binning'], text='\n' + labels[_] + '\n', tooltip=' height and width of the bin used for data binning').grid(row=_+1, column=1, padx=(10, 60), pady=0, sticky='w')
labels = ['Stick (deg)', 'Figure (deg)', 'Reference (deg)']
self.rotation = [CTk.StringVar(value='0'), CTk.StringVar(value='0'), CTk.StringVar(value='0')]
for _ in range(len(labels)):
tooltip = ' positive value for counter-clockwise rotation\n negative value for clockwise rotation'
if _ == 2:
tooltip = u' normalize \u03C1 with respect to this angle\n -if combined with figure rotation, reference angle is determined in the rotated figure'
Label(adv['Rotation'], text=labels[_] + '\n', tooltip=tooltip).grid(row=_+1, column=1, padx=(0, 10), pady=(6, 3), sticky='nw')
entry = CTk.CTkEntry(adv['Rotation'], textvariable=self.rotation[_], width=50, justify='center')
entry.grid(row=_+1, column=0, padx=20, pady=0, sticky='e')
if _ != 1:
entry.bind('<Return>', command=self.rotation_callback)
elif _ == 1:
entry.bind('<Return>', command=self.rotation1_callback)
self.noise = [CTk.StringVar(value='1'), CTk.StringVar(value='3'), CTk.StringVar(value='3')]
labels = ['Bin width', 'Bin height']
for _ in range(2):
SpinBox(adv['Intensity removal'], from_=3, to_=19, step_size=2, textvariable=self.noise[_+1]).grid(row=_+1, column=0, padx=(30, 10), pady=5, sticky='e')
Label(master=adv['Intensity removal'], text='\n' + labels[_] + '\n', tooltip=' height and width of the bin used for intensity removal').grid(row=_+1, column=1, padx=(10, 60), pady=0, sticky='w')
Label(master=adv['Intensity removal'], text='\nPick center of bin\n', tooltip=' pick center of the bin used for intensity removal').grid(row=3, column=1, padx=10, pady=0, sticky='w')
Button(adv['Intensity removal'], image=self.icons['removal'], command=lambda:self.click_callback(self.intensity_axis, self.intensity_pyfig.canvas, 'click background'), tooltip=' click button and select a point on the intensity image').grid(row=3, column=0, pady=5, padx=25, sticky='e')
CTk.CTkEntry(adv['Intensity removal'], textvariable=self.noise[0], width=50, justify='center').grid(row=4, column=0, sticky='e', padx=23)
Label(adv['Intensity removal'], text='\nFactor\n', tooltip=' fraction of the mean intensity value to be substracted\n value between 0 and 1').grid(row=4, column=1, padx=10, sticky='w')
self.intensity_removal_label = Label(master=adv['Intensity removal'], text='Removed intensity value = 0')
self.intensity_removal_label.grid(row=5, column=0, columnspan=2, padx=(40, 10), pady=0, sticky='w')
Label(master=adv['Intensity removal'], text=' ', height=5).grid(row=6, column=0)
## RIGHT FRAME: ABOUT
dict_buttons = {'row': 0, 'padx': 20, 'pady': 20, 'sticky': "nw"}
Button(self.tabview.tab('About'), image=self.icons['web'], command=lambda:self.openweb(type(self).url_fresnel), tooltip=' visit the polarimetry website').grid(column=0, **dict_buttons)
Button(self.tabview.tab('About'), image=self.icons['mail'], command=self.send_email, tooltip=' send an email to report bugs and/or send suggestions').grid(column=1, **dict_buttons)
Button(self.tabview.tab('About'), image=self.icons['GitHub'], command=lambda:self.openweb(type(self).url_github), tooltip=' visit the PyPOLAR GitHub page').grid(column=2, **dict_buttons)
Button(self.tabview.tab('About'), image=self.icons['contact_support'], command=lambda:self.openweb(type(self).url_wiki), tooltip=' visit the PyPOLAR wiki').grid(column=3, **dict_buttons)
about_textbox = TextBox(master=self.tabview.tab('About'), width=600, height=500, wrap='word')
about_textbox.write(f'Version: {type(self).__version__} ({type(self).__version_date__}) \n\n\n Website: {self.url_fresnel} \n\n\n Source code available at {self.url_github} \n\n\n\n PyPOLAR is based on a code originally developed by Sophie Brasselet (Institut Fresnel, CNRS) \n\n\n To report bugs, send an email to\n manos.mavrakis@cnrs.fr (Manos Mavrakis, Institut Fresnel, CNRS) \n {self.email} (Cristel Chandre, Institut de Mathématiques de Marseille, CNRS) \n sophie.brasselet@fresnel.fr (Sophie Brasselet, Institut Fresnel, CNRS) \n\n\n\n BSD 2-Clause License\n\n Copyright(c) 2021, Cristel Chandre\n All rights reserved. \n\n\n PyPOLAR was created using Python with packages Tkinter (CustomTkinter), NumPy, SciPy, OpenCV, scikit-image, Matplotlib, openpyxl, tksheet, colorcet, joblib \n\n\n PyPOLAR uses Material Design icons by Google')
about_textbox.grid(row=1, column=0, columnspan=4, padx=30, sticky="n")
self.startup()
def startup(self) -> None:
self.method.set('1PF')
self.option.set('Thresholding (manual)')
self.openfile_dropdown_value.set('Open file')
self.define_variable_table('1PF')
self.CD = Calibration('1PF')
self.calib_dropdown.configure(values=self.CD.list('1PF'))
self.calib_dropdown.set(self.CD.list('1PF')[0])
self.calib_textbox.write(self.CD.name)
self.polar_dropdown.set('UL90-UR0-LR135-LL45')
self.thrsh_colormap = 'hot'
self.tabview.set('Intensity')
self.filename_label.focus()
self.removed_intensity = 0
def initialize_slider(self) -> None:
if hasattr(self, 'datastack'):
self.stack_slider.configure(to=self.stack.nangle, number_of_steps=self.stack.nangle)
self.ilow.set(self.stack.display.format(np.amin(self.datastack.intensity)))
self.ilow_slider.set(float(self.ilow.get()) / float(np.amax(self.datastack.intensity)))
self.contrast_intensity_slider.set(1)
self.contrast_thrsh_slider.set(1)
self.stack_slider.set(0)
self.stack_slider_label.configure(text='T')
def initialize_noise(self) -> None:
vals = [1, 3, 3]
for val, _ in zip(vals, self.noise):
_.set(str(val))
self.removed_intensity = 0
self.intensity_removal_label.configure(text='Removed intensity value = 0')
def initialize(self) -> None:
self.initialize_slider()
self.initialize_noise()
if hasattr(self, 'datastack'):
self.datastack.rois = []
self.ontab_intensity()
self.ontab_thrsh()
def initialize_tables(self) -> None:
for show, save in zip(self.show_table, self.save_table):
show.deselect()
save.deselect()
if hasattr(self, 'variable_display'):
for var in self.variable_display:
var.set(0)
for ext in self.extension_table:
ext.deselect()
self.figure_extension_optionmenu.configure(state='disabled')
def click_save_output(self) -> None:
vec = [val.get() for val in self.save_table]
self.figure_extension_optionmenu.configure(state='normal' if any(vec)==1 else 'disabled')
def on_closing(self) -> None:
plt.close('all')
self.destroy()
def clear_frame(self, frame:CTk.CTkFrame) -> None:
for widget in frame.winfo_children():
widget.destroy()
frame.pack_forget()
def openweb(self, url:str) -> None:
webbrowser.open(url)
def send_email(self) -> None:
webbrowser.open('mailto:?to=' + type(self).email + '&subject=[PyPOLAR] question', new=1)
def on_click_tab(self) -> None:
self.tabview.set('About' if self.tabview.get()!='About' else 'Intensity')
def edge_button_callback(self) -> None:
if hasattr(self, 'stack'):
if hasattr(self, 'edge_contours'):
self.edge_button.configure(fg_color=orange[0])
delattr(self, 'edge_contours')
self.tabview.delete('Edge Detection')
self.ontab_thrsh()
else:
if not hasattr(self, 'edge_window'):
self.edge_button.configure(fg_color=blue[0])
self.edge_window = ShowInfo(message=' Image for edge detection', image=self.icons['multiline_chart'], button_labels=['Download', 'Compute', 'Cancel'], geometry=(370, 140), fontsize=16)
self.edge_window.protocol('WM_DELETE_WINDOW', self.cancel_edge_mask)
self.edge_window.bind('<Command-q>', self.cancel_edge_mask)
self.edge_window.bind('<Command-w>', self.cancel_edge_mask)
buttons = self.edge_window.get_buttons()
buttons[0].configure(command=self.download_edge_mask)
buttons[1].configure(command=self.compute_edge_mask)
buttons[2].configure(command=self.cancel_edge_mask)
else:
self.cancel_edge_mask()
def cancel_edge_mask(self) -> None:
self.edge_window.withdraw()
delattr(self, 'edge_window')
if hasattr(self, 'edge_contours'):
delattr(self, 'edge_contours')
self.edge_button.configure(fg_color=orange[0])
def download_edge_mask(self) -> None:
self.edge_window.withdraw()
delattr(self, 'edge_window')
filetypes = [('PNG files', '*.png')]
initialdir = self.stack.folder if hasattr(self, 'stack') else Path.home()
file = fd.askopenfilename(title='Select a mask file', initialdir=initialdir, filetypes=filetypes)
self.edge_method = 'download'
self.edge_detection_tab()
self.edge_mask = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
self.compute_edges()
def compute_edge_mask(self) -> None:
self.edge_window.withdraw()
delattr(self, 'edge_window')
self.edge_method = 'compute'
self.edge_detection_tab()
self.compute_edges()
def edge_detection_tab(self) -> None:
self.tabview.insert(4, 'Edge Detection')
adv_elts = ['Edge detection', 'Layer']
adv_sides = [CTk.LEFT, CTk.RIGHT]
adv = {}
for elt, side in zip(adv_elts, adv_sides):
adv.update({elt: CTk.CTkFrame(
master=self.tabview.tab('Edge Detection'), fg_color=gray[0])})
adv[elt].pack(side=side, padx=20, pady=(10, 10))
Label(master=adv[elt], text=elt + '\n', width=230, font=CTk.CTkFont(size=16)).grid(row=0, column=0, padx=20, pady=(10,0))
params = ['Low threshold', 'High threshold', 'Length', 'Smoothing window']
tooltips = [' hysteresis thresholding values: edges with intensity gradients\n below this value are not edges and discarded ', ' hysteresis thresholding values: edges with intensity gradients\n larger than this value are sure to be edges', ' minimum length for a contour (in pixels)', ' number of pixels in the window used for smoothing contours (in pixels)']
self.canny_thrsh = [CTk.StringVar(value='60'), CTk.StringVar(value='100'), CTk.StringVar(value='100'), CTk.StringVar(value='20')]
for _, (param, tooltip) in enumerate(zip(params, tooltips)):
entry = Entry(adv['Edge detection'], text=param, textvariable=self.canny_thrsh[_], row=_+1, tooltip=tooltip)
entry.bind('<Return>', command=self.compute_edges)
Label(master=adv['Edge detection'], text=' ').grid(row=5, column=0)
params = ['Distance from contour', 'Layer width']
tooltips = [' width of the region to be analyzed (in pixels)', ' distance from contour of the region to be analyzed (in pixels)']
self.layer_params = [CTk.StringVar(value='0'), CTk.StringVar(value='10')]
for _, (param, tooltip) in enumerate(zip(params, tooltips)):
Entry(adv['Layer'], text=param, textvariable=self.layer_params[_], row=_+1, tooltip=tooltip)
Label(master=adv['Layer'], text=' ').grid(row=3, column=0)
def compute_edges(self, event:tkEvent=None) -> None:
if self.edge_method == 'compute':
field = self.stack.intensity.copy()
thrsh = float(self.ilow.get())
field[field <= thrsh] = 0
field = (field / np.amax(field) * 255).astype(np.uint8)
field = cv2.GaussianBlur(field, (5, 5), 0)
edges = cv2.Canny(image=field, threshold1=float(self.canny_thrsh[0].get()), threshold2=float(self.canny_thrsh[1].get()))
self.edge_contours = self.smooth_contours(cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0])
self.ontab_thrsh()
elif self.edge_method == 'download':
self.edge_contours = self.smooth_contours(cv2.findContours(self.edge_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0])
self.ontab_thrsh()
def smooth_contours(self, contours:List) -> List:
window_length = int(self.canny_thrsh[3].get())
edge_contours = []
for contour in contours:
if (len(contour) >= int(self.canny_thrsh[2].get())):
edge_contours += [savgol_filter(contour.reshape((-1, 2)), window_length=window_length, polyorder=3, mode='nearest', axis=0)]
return edge_contours
def define_rho_ct(self, contours:List[np.ndarray]) -> np.ndarray:
rho_ct = np.nan * np.ones_like(self.stack.intensity)
for contour in contours:
angle, normal = angle_edge(contour)
crange = chain(range(-int(self.layer_params[0].get()) - int(self.layer_params[1].get()), -int(self.layer_params[0].get()) + 1), range(int(self.layer_params[0].get()), int(self.layer_params[0].get()) + int(self.layer_params[1].get()) + 1))
for _ in crange:
shift_x = (contour[:, 0] + _ * normal[:, 0]).astype(np.uint16)
shift_y = (contour[:, 1] + _ * normal[:, 1]).astype(np.uint16)
shift_x[shift_x <= 0] = 0
shift_y[shift_y <= 0] = 0
shift_x[shift_x >= self.stack.width - 1] = self.stack.width - 1
shift_y[shift_y >= self.stack.height - 1] = self.stack.height - 1
rho_ct[shift_y, shift_x] = angle
return rho_ct
def change_polarization_direction(self):
self.polar_dir.set('clockwise' if self.polar_dir.get() == 'counterclockwise' else 'counterclockwise')
self.polarization_button.configure(image=self.icons[self.polar_dir.get()])
def contrast_thrsh_slider_callback(self, value:float) -> None:
self.contrast_thrsh_slider.set(0.01 if value <= 0.01 else value)
self.ontab_thrsh()
def contrast_intensity_slider_callback(self, value:float) -> None:
self.contrast_intensity_slider.set(0.01 if value <= 0.01 else value)
self.ontab_intensity()
def contrast_intensity_button_callback(self) -> None:
value = self.contrast_intensity_slider.get()
self.contrast_intensity_slider.set(0.5 if value <= 0.5 else 1)
self.ontab_intensity()
def contrast_thrsh_button_callback(self) -> None:
self.contrast_thrsh_slider.set(0.5 if self.contrast_thrsh_slider.get() <= 0.5 else 1)
self.ontab_thrsh(update=True)
def roimanager_callback(self) -> None:
def on_closing(manager:ROIManager) -> None:
if hasattr(self, 'datastack'):
self.datastack.rois = manager.update_rois(self.datastack.rois)
self.ontab_intensity()
self.ontab_thrsh()
manager.destroy()
delattr(self, 'manager')
def on_edit(manager:ROIManager, rois, event=None) -> None:
rois = manager.update_rois(rois)
self.ontab_intensity()
self.ontab_thrsh()
def delete(manager:ROIManager) -> None:
if hasattr(self, 'datastack'):
manager.delete(self.datastack.rois)
self.ontab_intensity()
self.ontab_thrsh()
def load(manager:ROIManager) -> None:
if hasattr(self, 'datastack'):
self.datastack.rois = manager.load(initialdir=self.stack.folder if hasattr(self, 'stack') else Path.home())
self.ontab_intensity()
self.ontab_thrsh()
if not hasattr(self, 'manager'):
button_images = [self.icons['save'], self.icons['download'], self.icons['delete']]
self.manager = ROIManager(rois=self.datastack.rois if hasattr(self, 'datastack') else [], button_images=button_images)
self.manager.protocol('WM_DELETE_WINDOW', lambda:on_closing(self.manager))
self.manager.bind('<Command-q>', lambda:on_closing(self.manager))
self.manager.bind('<Command-w>', lambda:on_closing(self.manager))
buttons = self.manager.get_buttons()
buttons[0].configure(command=lambda:self.manager.save(self.datastack.rois, self.datastack.file))
buttons[1].configure(command=lambda:load(self.manager))
buttons[2].configure(command=lambda:delete(self.manager))
try:
self.manager.sheet.extra_bindings("edit_cell", func=lambda _:on_edit(self.manager, self.datastack.rois, _))
self.manager.sheet.extra_bindings("edit_header", func=lambda _:on_edit(self.manager, self.datastack.rois, _))
except:
pass
def add_axes_on_all_figures(self) -> None:
figs = list(map(plt.figure, plt.get_fignums()))
for fig in figs:
fs = fig.canvas.manager.get_window_title()
if (fig.type in ['Composite', 'Sticks', 'Intensity']):
if (hasattr(self, 'datastack') and (self.datastack.name in fs)) or self.openfile_dropdown_value.get() == 'Open figure':
fig.axes[0].axis(self.add_axes_checkbox.get())
fig.canvas.draw()
elif fig.type == 'Histogram' and (hasattr(self, 'datastack') and self.datastack.name in fs):
fig.axes[0].tick_params(labelcolor='k' if self.add_axes_checkbox.get() else 'w')
def colorbar_on_all_figures(self) -> None:
figs = list(map(plt.figure, plt.get_fignums()))
for fig in figs:
fs = fig.canvas.manager.get_window_title()
if (fig.type in ['Composite', 'Sticks', 'Intensity']) :
if (hasattr(self, 'datastack') and (self.datastack.name in fs)) or self.openfile_dropdown_value.get() == 'Open figure':
if self.colorbar_checkbox.get():
ax_divider = make_axes_locatable(fig.axes[0])
cax = ax_divider.append_axes('right', size='7%', pad='2%')
if fig.type == 'Composite':
fig.colorbar(fig.axes[0].images[1], cax=cax)
elif (fig.type == 'Sticks') or ((fig.type == 'Intensity') and hasattr(self, 'edge_contours')):
fig.colorbar(fig.axes[0].collections[0], cax=cax)
if (fig.type == 'Intensity') and (not hasattr(self, 'edge_contours')):
fig.axes[1].remove()
else:
if len(fig.axes) >= 2:
fig.axes[1].remove()
if self.openfile_dropdown_value.get() == 'Open figure':
plt.show()
def colorblind_on_all_figures(self) -> None:
figs = list(map(plt.figure, plt.get_fignums()))
for fig in figs:
fs = fig.canvas.manager.get_window_title()
if hasattr(self, 'datastack'):
for var in self.datastack.vars:
if (var.name == fig.var):
cmap = var.colormap[self.colorblind_checkbox.get()]
if fig.type == 'Intensity':
cmap = self.datastack.vars[0].colormap[self.colorblind_checkbox.get()]
if (fig.type == 'Composite') and (self.datastack.name in fs):
fig.axes[0].images[1].set_cmap(cmap)
elif ((fig.type == 'Sticks') or ((fig.type == 'Intensity') and hasattr(self, 'edge_contours'))) and (self.datastack.name in fs):
fig.axes[0].collections[0].set_cmap(cmap)
if fs.startswith('Disk Cone'):
fig.axes[0].images[0].set_cmap('hsv' if not self.colorblind_checkbox.get() else m_colorwheel)
fig.axes[1].images[0].set_cmap('jet' if not self.colorblind_checkbox.get() else 'viridis')
def options_dropdown_callback(self, option:str) -> None:
self.options_dropdown.get_icon().configure(image=self.icons['build_fill'] if option.endswith('(auto)') else self.icons['build'])
if option.startswith('Mask'):
initialdir = self.stack.folder if hasattr(self, 'stack') else Path.home()
self.maskfolder = Path(fd.askdirectory(title='Select the directory containing masks', initialdir=initialdir))
if hasattr(self, 'datastack'):
self.mask = self.get_mask(self.datastack)
self.ontab_thrsh()
self.tabview.tab('Thresholding/Mask').update()
def open_file_callback(self, value:str) -> None:
initialdir = self.stack.folder if hasattr(self, 'stack') else Path.home()
if hasattr(self, 'manager'):
self.manager.delete_manager()
self.filelist = []
self.edge_button.configure(fg_color=orange[0])
if hasattr(self, 'edge_contours'):
delattr(self, 'edge_contours')
self.tabview.delete('Edge Detection')
if value == 'Open file':
filetypes = [('Tiff files', '*.tiff'), ('Tiff files', '*.tif')]
file = Path(fd.askopenfilename(title='Select a file', initialdir=initialdir, filetypes=filetypes))
self.openfile_dropdown.get_icon().configure(image=self.icons['photo_fill'])
if file.suffix in ['.tiff', '.tif']:
self.options_dropdown.get_icon().configure(image=self.icons['build'])
self.options_dropdown.set_state('normal')
self.options_dropdown.set_values(['Thresholding (manual)', 'Mask (manual)'])
self.option.set('Thresholding (manual)')
if hasattr(self, 'mask'):
delattr(self, 'mask')
self.open_file(file)
elif value == 'Open folder':
folder = Path(fd.askdirectory(title='Select a directory', initialdir=initialdir))
self.openfile_dropdown.get_icon().configure(image=self.icons['folder_open'])
self.filelist = [file for file in sorted(folder.glob('*.tif*'))]
self.indxlist = 0
if any(self.filelist):
self.open_file(self.filelist[0])
self.options_dropdown.set_state('normal')
self.options_dropdown.set_values(['Thresholding (manual)', 'Thresholding (auto)', 'Mask (manual)', 'Mask (auto)'])
self.option.set('Thresholding (manual)')
else:
ShowInfo(message=' The folder does not contain TIFF or TIF files', image=self.icons['download_folder'], button_labels=['OK'], geometry=(340, 140))
elif value == 'Open figure':
file = Path(fd.askopenfilename(title='Download a previous polarimetry figure', initialdir=initialdir, filetypes=[('PyPOLAR pickle figure', '*.pyfig')]))
self.openfile_dropdown.get_icon().configure(image=self.icons['imagesmode'])
if file.suffix == '.pyfig':
fig = pickle.load(open(file, 'rb'))
fig.canvas.manager.set_window_title(fig.var + ' ' + fig.type)
fig.show()
if hasattr(self, 'stack'):
self.ilow.set(self.stack.display.format(np.amin(self.stack.intensity)))
self.ontab_thrsh(update=False)
def crop_figures_callback(self) -> None:
if len(plt.get_fignums()) and (not hasattr(self, 'crop_window')):
self.crop_window = CTk.CTkToplevel(self)
self.crop_window.title('Crop Manager')
self.crop_window.geometry(geometry_info((440, 230)))
self.crop_window.protocol('WM_DELETE_WINDOW', self.crop_on_closing)
self.crop_window.bind('<Command-q>', lambda:self.crop_on_closing)
self.crop_window.bind('<Command-w>', self.crop_on_closing)
Label(self.crop_window, text=' define xlim and ylim', image=self.icons['crop'], compound='left', font=CTk.CTkFont(size=16), width=250).grid(row=0, column=0, columnspan=3, padx=30, pady=20)
if not hasattr(self, 'xylim'):
if hasattr(self, 'datastack'):
vals = [1, self.datastack.width, 1, self.datastack.height]
elif self.openfile_dropdown_value.get() == 'Open figure':
fig = plt.gcf()
vals = [1, fig.width, 1, fig.height]
self.xylim = [CTk.StringVar(value=str(val)) for val in vals]
labels = [u'\u2B62 xlim', u'\u2B63 ylim']
positions = [(1, 1), (1, 2), (2, 1), (2, 2)]
for _, label in enumerate(labels):
Label(master=self.crop_window, text=label).grid(row=_+1, column=0, padx=(20, 0), pady=0)
for var, position in zip(self.xylim, positions):
Entry(master=self.crop_window, textvariable=var, row=position[0], column=position[1])
banner = CTk.CTkFrame(self.crop_window)
banner.grid(row=3, column=0, columnspan=3, padx=20)
Button(banner, text='Crop', anchor='center', command=self.crop_figures, width=80, height=button_size[1], tooltip=' crop figures using the chosen axis limits').grid(row=0, column=0, padx=10, pady=20)
Button(banner, text='Get', anchor='center', command=self.get_axes, width=80, height=button_size[1], tooltip=' get the axis limits of the active figure').grid(row=0, column=1, padx=10, pady=20)
Button(banner, text='Create ROI', anchor='center', command=self.createROIfromcrop, width=80, height=button_size[1], tooltip=' create a rectangular ROI with the limits defined above').grid(row=0, column=2, padx=10, pady=20)
Button(banner, text='Reset', anchor='center', command=self.reset_figures, width=80, height=button_size[1]).grid(row=0, column=3, padx=10, pady=20)
def crop_on_closing(self):
self.crop_window.destroy()
delattr(self, 'crop_window')
def crop_figures(self) -> None:
figs = list(map(plt.figure, plt.get_fignums()))
for fig in figs:
fs = fig.canvas.manager.get_window_title()
valid = (self.datastack.name in fs) if hasattr(self, 'datastack') else False
if (fig.type in ['Sticks', 'Composite', 'Intensity']) and (valid or self.openfile_dropdown_value.get()=='Open figure'):
fig.axes[0].set_xlim((int(self.xylim[0].get()), int(self.xylim[1].get())))
fig.axes[0].set_ylim((int(self.xylim[3].get()), int(self.xylim[2].get())))
if self.openfile_dropdown_value.get()=='Open figure':
plt.show()
def get_axes(self) -> None:
fig = plt.gcf()
if fig.type in ['Sticks', 'Composite', 'Intensity']:
ax = fig.axes[0]
self.xylim[0].set(int(ax.get_xlim()[0]))
self.xylim[1].set(int(ax.get_xlim()[1]))
self.xylim[2].set(int(ax.get_ylim()[1]))
self.xylim[3].set(int(ax.get_ylim()[0]))
else:
ShowInfo(message=' Select an active figure of the type\n Composite, Sticks or Intensity', image=self.icons['crop'], button_labels=['OK'])
def createROIfromcrop(self) -> None:
if hasattr(self, 'datastack'):
self.get_axes()
roix = np.asarray([int(self.xylim[0].get()), int(self.xylim[1].get()), int(self.xylim[1].get()), int(self.xylim[0].get())])
roiy = np.asarray([int(self.xylim[3].get()), int(self.xylim[3].get()), int(self.xylim[2].get()), int(self.xylim[2].get())])
if (float(self.rotation[1].get()) != 0) :
theta = -np.deg2rad(float(self.rotation[1].get()))
cosd, sind = np.cos(theta), np.sin(theta)
x0, y0 = self.datastack.width / 2, self.datastack.height / 2
vertices = np.asarray([x0 + (roix - x0) * cosd + (roiy - y0) * sind, y0 - (roix - x0) * sind + (roiy - y0) * cosd])
else:
vertices = np.asarray([roix, roiy])
indx = self.datastack.rois[-1]['indx'] + 1 if self.datastack.rois else 1
self.datastack.rois += [{'indx': indx, 'label': (vertices[0][0], vertices[1][0]), 'vertices': vertices, 'ILow': self.ilow.get(), 'name': '', 'group': '', 'select': True}]
self.thrsh_pyfig.canvas.draw()
self.ontab_intensity()
self.ontab_thrsh()
if hasattr(self, 'manager'):
self.manager.update_manager(self.datastack.rois)
def reset_figures(self) -> None:
if hasattr(self, 'datastack'):
vals = [1, self.datastack.width, 1, self.datastack.height]
elif self.openfile_dropdown_value.get() == 'Open figure':
fig = plt.gcf()
vals = [1, fig.width, 1, fig.height]
if hasattr(self, 'datastack') or self.openfile_dropdown_value.get() == 'Open figure':
for _, val in enumerate(vals):
self.xylim[_].set(val)
self.crop_figures()
def clear_patches(self, ax:plt.Axes, canvas:FigureCanvasTkAgg) -> None:
if ax.patches:
for p in ax.patches:
p.set_visible(False)
p.remove()
for txt in ax.texts:
txt.set_visible(False)
canvas.draw()
def export_mask(self) -> None:
if hasattr(self, 'datastack'):
window = ShowInfo(message=' Select output mask type: \n\n - ROI: export ROIs as segmentation mask \n - Intensity: export intensity-thresholded image as segmentation mask \n - ROI \u00D7 Intensity: export intensity-thresholded ROIs as segmentation mask', image=self.icons['open_in_new'], button_labels=['ROI', 'Intensity', 'ROI \u00D7 Intensity', 'Cancel'], geometry=(530, 200))
buttons = window.get_buttons()
buttons[0].configure(command=lambda:self.export_mask_callback(window, 0))
buttons[1].configure(command=lambda:self.export_mask_callback(window, 1))
buttons[2].configure(command=lambda:self.export_mask_callback(window, 2))
buttons[3].configure(command=lambda:self.export_mask_callback(window, 3))
def export_mask_callback(self, window:CTk.CTkToplevel, event:int) -> None:
roi_map, mask = self.compute_roi_map(self.datastack)
array = []
if event == 0:
array = (255 * (roi_map != 0)).astype(np.uint8)
elif event == 1:
array = (255 * (self.datastack.intensity >= float(self.ilow.get()))).astype(np.uint8)
elif event == 2:
array = (255 * mask).astype(np.uint8)
if np.any(array):
data = Image.fromarray(array)
data.save(self.datastack.file.with_suffix('.png'))
window.withdraw()
def change_colormap(self) -> None:
self.thrsh_colormap = 'gray' if self.thrsh_colormap == 'hot' else 'hot'
self.ontab_thrsh()
def no_background(self) -> None:
if hasattr(self, 'stack'):
if self.thrsh_fig.patch.get_facecolor() == mpl.colors.to_rgba('k', 1):
self.thrsh_fig.patch.set_facecolor(gray[1])
self.no_background_button.configure(image=self.icons['photo_fill'])
else:
self.thrsh_fig.patch.set_facecolor('k')
self.no_background_button.configure(image=self.icons['photo'])
self.thrsh_pyfig.canvas.draw()
def offset_angle_switch_callback(self) -> None:
self.offset_angle_entry.set_state('normal' if self.offset_angle_switch.get() == 'on' else 'disabled')
def dark_switch_callback(self) -> None:
if hasattr(self, 'stack'):
if self.dark_switch.get() == 'on':
self.dark_entry.set_state('normal')
self.dark.set(self.stack.display.format(self.calculated_dark))
else:
self.dark_entry.set_state('disabled')
self.dark.set(self.stack.display.format(self.calculated_dark))
self.intensity_callback(event=1)
else:
self.dark.set('')
def calib_dropdown_callback(self, label:str) -> None:
self.CD = Calibration(self.method.get(), label=label)
self.offset_angle.set(str(self.CD.offset_default))
self.calib_textbox.write(self.CD.name)
def show_individual_fit_callback(self) -> None:
if not self.method.get().endswith('4POLAR') and hasattr(self, 'datastack'):
figs = list(map(plt.figure, plt.get_fignums()))
fig_ = None
for fig in figs:
fs = fig.canvas.manager.get_window_title()
if fig.var == 'Rho' and fig.type == 'Composite' and (self.datastack.name in fs):
fig_ = fig
break
if fig_ is not None:
plt.figure(fig_)
cfm = plt.get_current_fig_manager()
cfm.window.attributes('-topmost', True)
cfm.window.tkraise()
self.click_callback(fig_.axes[0], fig_.canvas, 'individual fit')
cfm.window.attributes('-topmost', False)
else:
ShowInfo(message=' provide a Rho Composite figure\n to plot individual fits', image=self.icons['query_stats'], button_labels=['OK'])
def diskcone_display(self) -> None:
if self.method.get() == '1PF' and hasattr(self, 'CD'):
self.CD.display(colorblind=self.colorblind_checkbox.get())
def variable_table_switch_callback(self) -> None:
state = 'normal' if self.variable_table_switch.get() == 'on' else 'disabled'
for entry in self.variable_entries[2:]:
entry.set_state(state)
def click_callback(self, ax:plt.Axes, canvas:FigureCanvasTkAgg, method:str) -> None:
if hasattr(self, 'datastack'):
if method == 'click background':
self.tabview.set('Intensity')
xlim, ylim = ax.get_xlim(), ax.get_ylim()
hlines = [plt.Line2D([(xlim[0] + xlim[1])/2, (xlim[0] + xlim[1])/2], ylim, lw=1, color='w'),
plt.Line2D(xlim, [(ylim[0] + ylim[1])/2, (ylim[0] + ylim[1])/2], lw=1, color='w')]
ax.add_line(hlines[0])
ax.add_line(hlines[1])
self.__cid1 = canvas.mpl_connect('motion_notify_event', lambda event: self.click_motion_notify_callback(event, hlines, ax, canvas))
if method == 'click background':
self.__cid2 = canvas.mpl_connect('button_press_event', lambda event: self.click_background_button_press_callback(event, hlines, ax, canvas))
elif method == 'individual fit':
self.__cid2 = canvas.mpl_connect('button_press_event', lambda event: self.individual_fit_button_press_callback(event, hlines, ax, canvas))
def click_motion_notify_callback(self, event:MouseEvent, hlines:List[mpl.lines.Line2D], ax:plt.Axes, canvas:FigureCanvasTkAgg) -> None:
if event.inaxes == ax:
x, y = event.xdata, event.ydata
xlim, ylim = ax.get_xlim(), ax.get_ylim()
if event.button is None:
hlines[0].set_data([x, x], ylim)
hlines[1].set_data(xlim, [y, y])
canvas.draw()
def click_background_button_press_callback(self, event:MouseEvent, hlines:List[mpl.lines.Line2D], ax:plt.Axes, canvas:FigureCanvasTkAgg) -> None:
if event.inaxes == ax:
x, y = event.xdata, event.ydata
if event.button == 1:
x1, x2 = int(round(x)) - int(self.noise[1].get())//2, int(round(x)) + int(self.noise[1].get())//2
y1, y2 = int(round(y)) - int(self.noise[2].get())//2, int(round(y)) + int(self.noise[2].get())//2
self.removed_intensity = int(np.mean(self.datastack.intensity[y1:y2, x1:x2]) / self.stack.nangle * float(self.noise[0].get()))
self.intensity_removal_label.configure(text=f'Removed intensity value = {self.removed_intensity}')
canvas.mpl_disconnect(self.__cid1)
canvas.mpl_disconnect(self.__cid2)
for line in hlines:
line.remove()
canvas.draw()
def compute_angle(self) -> None:
if hasattr(self, 'stack'):
self.intensity_pyfig.toolbar.mode = _Mode.NONE
self.intensity_pyfig.toolbar._update_buttons_checked()
self.tabview.set('Intensity')
self.compute_angle_button.configure(fg_color=orange[1])
hroi = ROI()
self.__cid1 = self.intensity_pyfig.canvas.mpl_connect('motion_notify_event', lambda event: self.compute_angle_motion_notify_callback(event, hroi))
self.__cid2 = self.intensity_pyfig.canvas.mpl_connect('button_press_event', lambda event: self.compute_angle_button_press_callback(event, hroi))
def compute_angle_motion_notify_callback(self, event:MouseEvent, roi:ROI) -> None:
if event.inaxes == self.intensity_axis:
x, y = event.xdata, event.ydata
if ((event.button is None or event.button == 1) and roi.lines):
roi.lines[-1].set_data([roi.previous_point[0], x], [roi.previous_point[1], y])
self.intensity_pyfig.canvas.draw()
def compute_angle_button_press_callback(self, event:MouseEvent, roi:ROI) -> None:
if event.inaxes == self.intensity_axis:
x, y = event.xdata, event.ydata
if event.button == 1:
if not roi.lines:
roi.lines = [plt.Line2D([x, x], [y, y], lw=3, color='w')]
roi.start_point = [x, y]
roi.previous_point = roi.start_point
self.intensity_axis.add_line(roi.lines[0])
self.intensity_pyfig.canvas.draw()
else:
roi.lines += [plt.Line2D([roi.previous_point[0], x], [roi.previous_point[1], y], lw=3, color='w')]
roi.previous_point = [x, y]
self.intensity_axis.add_line(roi.lines[-1])
self.intensity_pyfig.canvas.draw()
self.intensity_pyfig.canvas.mpl_disconnect(self.__cid1)
self.intensity_pyfig.canvas.mpl_disconnect(self.__cid2)
slope = 180 - np.rad2deg(np.arctan((roi.previous_point[1] - roi.start_point[1]) / (roi.previous_point[0] - roi.start_point[0])))
slope = np.mod(2 * slope, 360) / 2
dist = np.sqrt(((np.asarray(roi.previous_point) - np.asarray(roi.start_point))**2).sum())
message = ' Angle is {:.1f}\u00b0 \n Distance is {} pixels'.format(slope, int(dist))
if int(self.pixel_size.get()) != 0:
message += ' \n Distance is {:.1f} \xb5m'.format(int(dist) * int(self.pixel_size.get()) / 1000)
ShowInfo(message=message, image=self.icons['square'], button_labels = ['OK'], fontsize=14)
for line in roi.lines:
line.remove()
self.intensity_pyfig.canvas.draw()