-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGUI.py
More file actions
1879 lines (1763 loc) · 72 KB
/
GUI.py
File metadata and controls
1879 lines (1763 loc) · 72 KB
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
"""
Author: James Lamb
UI for running distortion correction
"""
# Python packages
import os
# from threading import Thread
from multiprocessing.pool import ThreadPool
import shutil
import tkinter as tk
from tkinter import filedialog, ttk, messagebox
# 3rd party packages
import h5py
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, transform
import torch
from torchvision.transforms.functional import resize as RESIZE
from torchvision.transforms import InterpolationMode
from kornia.enhance import equalize_clahe
# Local files
import warping
import Inputs
import InteractiveView as IV
# TODO: Exporting 3D data has not been tested
# TODO: Handle errors when reading in files
# TODO: Fix toplevel behavior of IO windows
# TODO: Add saving the state so that the user can come back to it later more easily (basically save the filepaths to everything)
# TODO: Change the way the points are saved so that the filename is more clear
def CLAHE(im, clip_limit=20.0, kernel_size=(8, 8)):
tensor = torch.tensor(im).unsqueeze(0).unsqueeze(0).float()
tensor = (tensor - tensor.min()) / (tensor.max() - tensor.min())
tensor = equalize_clahe(tensor, clip_limit, kernel_size)
tensor = torch.round(
255 * (tensor - tensor.min()) / (tensor.max() - tensor.min()), decimals=0
)
return np.squeeze(tensor.detach().numpy().astype(np.uint8)).reshape(im.shape)
class App(tk.Tk):
def __init__(self, screenName=None, baseName=None):
super().__init__(screenName, baseName)
self._style_call("dark")
#
# Starting stuff
self.update_idletasks()
self.withdraw()
self.folder = os.getcwd()
self.deiconify()
self.title("Distortion Correction")
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
# self.geometry(f"{int(screen_width*2/3)}x{int(screen_height*2/3)}")
self.resizable(False, False)
#
# Frames
self.columnconfigure((0, 2), weight=5)
self.columnconfigure(1, weight=1)
self.rowconfigure((0, 4), weight=5)
self.rowconfigure((1, 4), weight=1)
self.rowconfigure(2, weight=10)
self.top = ttk.Frame(self)
separator1 = ttk.Separator(self, orient=tk.HORIZONTAL)
self.viewer_left = ttk.Frame(self)
separator2 = ttk.Separator(self, orient=tk.VERTICAL)
self.viewer_right = ttk.Frame(self)
separator3 = ttk.Separator(self, orient=tk.HORIZONTAL)
self.bot_left = ttk.Frame(self)
separator4 = ttk.Separator(self, orient=tk.VERTICAL)
self.bot_right = ttk.Frame(self)
self.top.grid(row=0, column=0, columnspan=3, sticky="nsew", padx=5, pady=5)
self.viewer_left.grid(row=2, column=0, sticky="nsew", padx=5, pady=5)
self.viewer_right.grid(row=2, column=2, sticky="nsew", padx=5, pady=5)
self.bot_left.grid(row=4, column=0, sticky="nsew", padx=5, pady=5)
self.bot_right.grid(row=4, column=2, sticky="nsew", padx=5, pady=5)
separator1.grid(row=1, column=0, columnspan=3, sticky="ew")
separator2.grid(row=2, column=1, sticky="ns")
separator3.grid(row=3, column=0, columnspan=3, sticky="ew")
separator4.grid(row=4, column=1, sticky="ns")
#
# setup menubar
self.menu = tk.Menu(self)
filemenu = tk.Menu(self.menu, tearoff=0)
filemenu.add_command(
label="Open 2D", command=lambda: self.select_data_popup("2D")
)
filemenu.add_command(
label="Export 2D", command=self.apply_and_export_2d, state="disabled"
)
filemenu.add_command(
label="Open 3D", command=lambda: self.select_data_popup("3D")
)
filemenu.add_command(
label="Export 3D", command=self.apply_and_export_3d, state="disabled"
)
filemenu.add_command(
label="Export transform", command=self.export_transform, state="disabled"
)
filemenu.add_command(label="Quick start", command=self.easy_start)
self.menu.add_cascade(label="File", menu=filemenu)
applymenu2d = tk.Menu(self.menu, tearoff=0)
labels = [
"TPS",
"Affine only TPS",
]
keywords = [
"tps",
"tps affine",
]
for label, keyword in zip(labels, keywords):
applymenu2d.add_command(
label=label,
command=lambda keyword=keyword: self.apply_2d(keyword),
)
self.menu.add_cascade(
label="View transform (current image)", menu=applymenu2d, state="disabled"
)
applymenu3d = tk.Menu(self.menu, tearoff=0)
for label, keyword in zip(labels, keywords):
applymenu3d.add_command(
label=label,
command=lambda keyword=keyword: self.apply_3d(keyword),
)
self.menu.add_cascade(
label="View transform (image stack)", menu=applymenu3d, state="disabled"
)
self.config(menu=self.menu)
#
# setup top
self.show_points = tk.IntVar()
self.show_points.set(1)
self.view_pts = ttk.Checkbutton(
self.top,
text="Show points",
variable=self.show_points,
onvalue=1,
offvalue=0,
command=self._show_points,
state="disabled",
)
self.view_pts.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.top, orient=tk.VERTICAL)
sep.grid(row=0, column=1, sticky="ns")
self.slice_num = tk.IntVar()
self.slice_options = np.arange(0, 2, 1)
self.slice_num.set(self.slice_options[0])
slice_num_label = ttk.Label(self.top, text="Slice number:")
slice_num_label.grid(row=0, column=2, sticky="e", padx=5, pady=5)
self.slice_picker = ttk.Combobox(
self.top,
textvariable=self.slice_num,
values=list(self.slice_options),
height=10,
width=5,
)
self.slice_picker["state"] = "disabled"
self.slice_picker.bind("<<ComboboxSelected>>", self._update_viewers)
self.slice_picker.grid(row=0, column=3, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.top, orient=tk.VERTICAL)
sep.grid(row=0, column=4, sticky="ns")
#
# setup viewer_left
l = ttk.Label(self.viewer_left, text="EBSD/Distorted image", anchor=tk.CENTER)
l.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)
self.ebsd = tk.Canvas(
self.viewer_left,
highlightbackground=self.bg,
bg=self.bg,
bd=1,
highlightthickness=0.2,
cursor="tcross",
width=int(screen_width * 0.45),
height=int(screen_height * 0.7),
)
self.ebsd.grid(row=1, column=0, padx=5, pady=5, sticky="nsew")
self.ebsd_hscroll = ttk.Scrollbar(
self.viewer_left,
orient=tk.HORIZONTAL,
command=self.ebsd.xview,
cursor="sb_h_double_arrow",
)
self.ebsd_hscroll.grid(row=2, column=0, sticky="ew", padx=5, pady=5)
self.ebsd_vscroll = ttk.Scrollbar(
self.viewer_left,
orient=tk.VERTICAL,
command=self.ebsd.yview,
cursor="sb_v_double_arrow",
)
self.ebsd_vscroll.grid(row=1, column=1, sticky="ns", padx=5, pady=5)
self.ebsd.config(
xscrollcommand=self.ebsd_hscroll.set, yscrollcommand=self.ebsd_vscroll.set
)
#
# setup viewer right
l = ttk.Label(self.viewer_right, text="BSE/Control image", anchor=tk.CENTER)
l.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)
self.bse = tk.Canvas(
self.viewer_right,
highlightbackground=self.bg,
bg=self.bg,
bd=1,
highlightthickness=0.2,
cursor="tcross",
width=int(screen_width * 0.45),
height=int(screen_height * 0.7),
)
self.bse.grid(row=1, column=0, pady=5, padx=5, sticky="nsew")
self.bse_hscroll = ttk.Scrollbar(
self.viewer_right,
orient=tk.HORIZONTAL,
command=self.bse.xview,
cursor="sb_h_double_arrow",
)
self.bse_hscroll.grid(row=2, column=0, sticky="ew", padx=5, pady=5)
self.bse_vscroll = ttk.Scrollbar(
self.viewer_right,
orient=tk.VERTICAL,
command=self.bse.yview,
cursor="sb_v_double_arrow",
)
self.bse_vscroll.grid(row=1, column=1, sticky="ns", padx=5, pady=5)
self.bse.config(
xscrollcommand=self.bse_hscroll.set, yscrollcommand=self.bse_vscroll.set
)
#
# Bindings on viewers
if os.name == "posix":
remove_ = "<Button 2>"
scalar_ = 1
else:
remove_ = "<Button 3>"
scalar_ = 120
self.ebsd.bind(remove_, lambda arg: self.remove_coords("ebsd", arg))
self.ebsd.bind(
"<MouseWheel>",
lambda event: self.ebsd.yview_scroll(
int(-1 * (event.delta / scalar_)), "units"
),
)
self.ebsd.bind(
"<Shift-MouseWheel>",
lambda event: self.ebsd.xview_scroll(
int(-1 * (event.delta / scalar_)), "units"
),
)
self.bse.bind(remove_, lambda arg: self.remove_coords("bse", arg))
self.bse.bind(
"<MouseWheel>",
lambda event: self.bse.yview_scroll(
int(-1 * (event.delta / scalar_)), "units"
),
)
self.bse.bind(
"<Shift-MouseWheel>",
lambda event: self.bse.xview_scroll(
int(-1 * (event.delta / scalar_)), "units"
),
)
self.ebsd.bind("<ButtonPress-1>", lambda arg: self.add_coords("ebsd", arg))
self.bse.bind("<ButtonPress-1>", lambda arg: self.add_coords("bse", arg))
self.bind("<Control-equal>", lambda event: self.change_zoom_event(+1), "units")
self.bind("<Control-minus>", lambda event: self.change_zoom_event(-1), "units")
# self.ebsd.bind('<Control-equal>', lambda event: self.change_zoom_event(+1, "ebsd"), "units")
# self.ebsd.bind('<Control-minus>', lambda event: self.change_zoom_event(-1, "ebsd"), "units")
# self.bse.bind('<Control-equal>', lambda event: self.change_zoom_event(+1, "bse"), "units")
# self.bse.bind('<Control-minus>', lambda event: self.change_zoom_event(-1, "bse"), "units")
#
# setup bottom left
self.clear_ebsd_points = ttk.Button(
self.bot_left,
text="Clear points",
command=lambda: self.clear_points("ebsd"),
state="disabled",
)
self.clear_ebsd_points.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.bot_left, orient=tk.VERTICAL)
sep.grid(row=0, column=1, sticky="ns")
ebsd_mode_label = ttk.Label(self.bot_left, text="EBSD mode:")
ebsd_mode_label.grid(row=0, column=2, sticky="e", padx=5, pady=5)
self.ebsd_mode = tk.StringVar()
self.ebsd_mode_options = ["Intensity"]
self.ebsd_mode.set(self.ebsd_mode_options[0])
self.ebsd_picker = ttk.Combobox(
self.bot_left,
textvariable=self.ebsd_mode,
values=self.ebsd_mode_options,
height=10,
width=20,
)
self.ebsd_picker["state"] = "disabled"
self.ebsd_picker.bind("<<ComboboxSelected>>", self._update_viewers)
self.ebsd_picker.grid(row=0, column=3, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.bot_left, orient=tk.VERTICAL)
sep.grid(row=0, column=4, sticky="ns")
self.clahe_ebsd_b = ttk.Button(
self.bot_left,
text="Apply CLAHE",
command=lambda *args: self.clahe("ebsd"),
state="disabled",
)
self.clahe_ebsd_b.grid(row=0, column=5, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.bot_left, orient=tk.VERTICAL)
sep.grid(row=0, column=6, sticky="ns")
# setup bottom right
self.clear_bse_points = ttk.Button(
self.bot_right,
text="Clear points",
command=lambda: self.clear_points("bse"),
state="disabled",
)
self.clear_bse_points.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.bot_right, orient=tk.VERTICAL)
sep.grid(row=0, column=1, sticky="ns")
bse_mode_label = ttk.Label(self.bot_right, text="EBSD mode:")
bse_mode_label.grid(row=0, column=2, sticky="e", padx=5, pady=5)
self.bse_mode = tk.StringVar()
self.bse_mode_options = ["Intensity"]
self.bse_mode.set(self.bse_mode_options[0])
self.bse_picker = ttk.Combobox(
self.bot_right,
textvariable=self.bse_mode,
values=self.bse_mode_options,
height=10,
width=20,
)
self.bse_picker["state"] = "disabled"
self.bse_picker.bind("<<ComboboxSelected>>", self._update_viewers)
self.bse_picker.grid(row=0, column=3, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.bot_right, orient=tk.VERTICAL)
sep.grid(row=0, column=4, sticky="ns")
self.clahe_bse_b = ttk.Button(
self.bot_right,
text="Apply CLAHE",
command=lambda *args: self.clahe("bse"),
state="disabled",
)
self.clahe_bse_b.grid(row=0, column=5, sticky="ew", padx=5, pady=5)
sep = ttk.Separator(self.bot_right, orient=tk.VERTICAL)
sep.grid(row=0, column=6, sticky="ns")
# Setup resizing
self.resize_options = [
1,
5,
10,
25,
50,
75,
100,
125,
150,
175,
200,
300,
400,
600,
]
self.resize_var_ebsd = tk.StringVar()
self.resize_var_bse = tk.StringVar()
self.resize_var_ebsd.set(self.resize_options[3])
self.resize_var_bse.set(self.resize_options[3])
self.resize_var_ebsd.trace_add(
"write", lambda *args: self._resize("ebsd", self.resize_vars["ebsd"].get())
)
self.resize_var_bse.trace_add(
"write", lambda *args: self._resize("bse", self.resize_vars["bse"].get())
)
ebsd_resize_label = ttk.Label(self.bot_left, text="Zoom:")
bse_resize_label = ttk.Label(self.bot_right, text="Zoom:")
ebsd_resize_label.grid(row=0, column=7, sticky="e", padx=5, pady=5)
bse_resize_label.grid(row=0, column=7, sticky="e", padx=5, pady=5)
self.ebsd_resize_dropdown = ttk.Combobox(
self.bot_left,
textvariable=self.resize_var_ebsd,
values=self.resize_options,
state="readonly",
width=5,
)
self.bse_resize_dropdown = ttk.Combobox(
self.bot_right,
textvariable=self.resize_var_bse,
values=self.resize_options,
state="readonly",
width=5,
)
self.ebsd_resize_dropdown["state"] = "disabled"
self.bse_resize_dropdown["state"] = "disabled"
self.ebsd_resize_dropdown.grid(row=0, column=8, sticky="ew")
self.bse_resize_dropdown.grid(row=0, column=8, sticky="ew")
self.resize_vars = {"ebsd": self.resize_var_ebsd, "bse": self.resize_var_bse}
### Additional things added
self.clahe_active_bse = False
self.clahe_active_ebsd = False
self.points = {"ebsd": {}, "bse": {}}
self.points_path = {"ebsd": "", "bse": ""}
def _thread_function(self, function, *args):
output = function(*args)
self.event_generate("<<Foo>>", when="tail")
return output
def _run_in_background(self, text, function, *args):
self.w = ProgressWindow(text)
self.bind("<<Foo>>", lambda arg: self.w.destroy())
thread_obj = ThreadPool(processes=1)
output = thread_obj.apply_async(self._thread_function, (function, *args))
self.wait_window(self.w)
return output.get()
def change_zoom_event(self, change):
print("Changing zoom !", change)
index = self.resize_options.index(int(self.resize_var_bse.get()))
index = max(0, min(len(self.resize_options) - 1, index + change))
self.resize_var_bse.set(self.resize_options[index])
index = self.resize_options.index(int(self.resize_var_ebsd.get()))
index = max(0, min(len(self.resize_options) - 1, index + change))
self.resize_var_ebsd.set(self.resize_options[index])
### IO ###
def easy_start(self):
# ebsd_path = "./test_data/EBSD.ang"
# ebsd_points_path = "./test_data/distorted_pts.txt"
# bse_path = "./test_data/BSE.tif"
# bse_points_path = "./test_data/control_pts.txt"
# ebsd_res = 2.5
# bse_res = 1.0
# rescale = True
# r180 = False
# flip = False
# crop = False
ebsd_points_path = (
"/Users/jameslamb/Documents/research/data/CoNi90-thin/distorted_pts.txt"
)
bse_points_path = (
"/Users/jameslamb/Documents/research/data/CoNi90-thin/control_pts.txt"
)
ebsd_path = (
"/Users/jameslamb/Documents/research/data/CoNi90-thin/CoNi90-thin.dream3d"
)
bse_path = "/Users/jameslamb/Documents/research/data/CoNi90-thin/CoNi90-thin_BSE_small.dream3d"
ebsd_res = 1.0
bse_res = 1.0
rescale = False
r180 = False
flip = True
crop = False
self.ang_path = ebsd_path
self.ebsd_res = ebsd_res
self.bse_res = bse_res
e_d, b_d, e_pts, b_pts = self._run_in_background(
"Importing data...",
Inputs.read_data,
ebsd_path,
bse_path,
ebsd_points_path,
bse_points_path,
)
if e_pts is None:
e_pts = {0: []}
ebsd_points_path = os.path.dirname(ebsd_path) + "/distorted_pts.txt"
with open(ebsd_points_path, "w", encoding="utf8") as output:
output.write("")
if b_pts is None:
b_pts = {0: []}
bse_points_path = os.path.dirname(ebsd_path) + "/control_pts.txt"
with open(bse_points_path, "w", encoding="utf8") as output:
output.write("")
if rescale:
b_d = Inputs.rescale_control(b_d, bse_res, ebsd_res)
# Flip or rotate 180 if desired
if flip or r180:
b_d = Inputs.flip_rotate_control(b_d, flip, r180)
# Crop if desired
if crop:
### TODO: Add multiple control images
self.w = Inputs.CropControl(self, b_d[0, :, :])
self.wait_window(self.w.w)
if self.w.clean_exit:
s, e = self.w.start, self.w.end
### TODO: Add multiple control images
b_d = b_d[:, s[0] : e[0], s[1] : e[1]]
self._handle_input(
ebsd_path,
bse_path,
e_d,
b_d,
ebsd_points_path,
bse_points_path,
e_pts,
b_pts,
ebsd_res,
bse_res,
)
def select_data_popup(self, mode):
self.w = Inputs.DataInput(self, mode)
self.wait_window(self.w.w)
self.update()
if self.w.clean_exit:
if self.w.ang:
self.ang_path = self.w.ebsd_path
ebsd_path, bse_path = self.w.ebsd_path, self.w.bse_path
ebsd_points_path, bse_points_path = (
self.w.ebsd_points_path,
self.w.bse_points_path,
)
ebsd_res, bse_res = self.w.ebsd_res, self.w.bse_res
e_d, b_d, e_pts, b_pts = Inputs.read_data(
ebsd_path, bse_path, ebsd_points_path, bse_points_path
)
self.w = Inputs.DataSummary(self, e_d, b_d, e_pts, b_pts, ebsd_res, bse_res)
self.wait_window(self.w.w)
self.update()
if self.w.clean_exit:
if e_pts is None:
e_pts = {0: []}
ebsd_points_path = os.path.dirname(ebsd_path) + "/distorted_pts.txt"
with open(ebsd_points_path, "w", encoding="utf8") as output:
output.write("")
if b_pts is None:
b_pts = {0: []}
bse_points_path = os.path.dirname(ebsd_path) + "/control_pts.txt"
with open(bse_points_path, "w", encoding="utf8") as output:
output.write("")
# Rescale if desired
if self.w.rescale:
b_d = Inputs.rescale_control(b_d, bse_res, ebsd_res)
# Flip or rotate 180 if desired
if self.w.flip or self.w.r180:
b_d = Inputs.flip_rotate_control(b_d, self.w.flip, self.w.r180)
# Crop if desired
if self.w.crop:
im = b_d[list(b_d.keys())[0]][0]
self.w = Inputs.CropControl(self, im)
self.wait_window(self.w.w)
self.update()
if self.w.clean_exit:
s, e = self.w.start, self.w.end
for key in b_d.keys():
b_d[key] = b_d[key][:, s[0] : e[0], s[1] : e[1]]
self._handle_input(
ebsd_path,
bse_path,
e_d,
b_d,
ebsd_points_path,
bse_points_path,
e_pts,
b_pts,
ebsd_res,
bse_res,
)
else:
return
def _handle_input(
self,
ebsd_path,
bse_path,
e_d,
b_d,
ebsd_points_path,
bse_points_path,
e_pts,
b_pts,
ebsd_res,
bse_res,
):
# Set the data
self.points_path = {"ebsd": ebsd_points_path, "bse": bse_points_path}
self.ebsd_path, self.bse_path = ebsd_path, bse_path
self.ebsd_data, self.bse_data = e_d, b_d
self.ebsd_res, self.bse_res = ebsd_res, bse_res
self.points["ebsd"], self.points["bse"] = e_pts, b_pts
# Set the UI stuff
self.ebsd_mode_options = list(self.ebsd_data.keys())
self.ebsd_mode.set(self.ebsd_mode_options[0])
self.bse_mode_options = list(self.bse_data.keys())
self.bse_mode.set(self.bse_mode_options[0])
self.slice_min = 0
self.slice_max = self.ebsd_data[self.ebsd_mode_options[0]].shape[0] - 1
self.slice_num.set(self.slice_min)
# Update slice picker values
self.slice_picker["values"] = list(
np.arange(self.slice_min, self.slice_max + 1)
)
# Turn on GUI elements that are always on
self.menu.entryconfig("View transform (current image)", state="normal")
self.menu.nametowidget(self.menu.entrycget("File", "menu")).entryconfig(
"Export transform", state="normal"
)
self.menu.nametowidget(self.menu.entrycget("File", "menu")).entryconfig(
"Export 2D", state="normal"
)
# self.menu.entryconfig("Export transform", state="normal")
# self.menu.entryconfig("Export 2D", state="normal")
self.ebsd_picker["state"] = "readonly"
self.ebsd_picker["values"] = self.ebsd_mode_options
self.bse_picker["state"] = "readonly"
self.bse_picker["values"] = self.bse_mode_options
# Turn on dimensionality specific elements
if self.slice_max == self.slice_min: # 2D data
self.slice_picker["state"] = "disabled"
else: # 3D data
self.slice_picker["state"] = "readonly"
self.menu.entryconfig("Apply transform (all images)", state="normal")
self.menu.nametowidget(self.menu.entrycget("File", "menu")).entryconfig(
"Export 3D", state="normal"
)
# Finish
self.folder = os.path.dirname(ebsd_path)
self._update_viewers()
self.clear_ebsd_points["state"] = "normal"
self.clear_bse_points["state"] = "normal"
self.ebsd_resize_dropdown["state"] = "readonly"
self.bse_resize_dropdown["state"] = "readonly"
self.clahe_bse_b["state"] = "normal"
self.clahe_ebsd_b["state"] = "normal"
self.view_pts["state"] = "normal"
self.show_points.set(1)
def export_transform(self):
save_path = filedialog.asksaveasfilename(
initialdir=self.folder,
title="Save the transform",
filetypes=(
("Binary NumPy Array", ("*.npy")),
("CSV files", "*.csv"),
("Text files", "*.txt"),
("All files", "*.*"),
),
)
if save_path == "":
return
delimiter = "," if save_path.endswith(".csv") else " "
# Get the mode
mode = ArbitraryMessageBox(
self,
title="Mode",
msg="Select the mode to use for the correction.",
options=[
"Thin-Plate Spline",
"Thin-Plate Spline (Affine only)",
],
orientation="vertical",
)
if mode is None:
return
elif mode == False:
return
else:
mode = [
"tps",
"tps affine",
][mode.choice]
print("Mode choice:", mode)
# Get the shape of the BSE image and the points
dst_img_shape = self.bse_data[self.bse_mode.get()][self.slice_num.get()].shape
src_points = np.array(self.points["ebsd"][self.slice_num.get()])
dst_points = np.array(self.points["bse"][self.slice_num.get()])
if src_points.size == 0 or dst_points.size == 0:
messagebox.showerror(
"Error",
"No points selected for the transformation. Please select points.",
)
return
# Get the transform for the EBSD data
if "tps" in mode.lower():
tform = warping.get_transform(
src_points, dst_points, mode=mode, size=dst_img_shape
)
else:
tform = warping.get_transform(src_points, dst_points, mode=mode)
params = tform.params
# Save the transform
print("Saving transform to:", save_path)
if save_path.endswith(".npy"):
np.save(save_path, params)
else:
params = params.reshape(2, -1).T
np.savetxt(
save_path,
params,
delimiter=delimiter,
header=f"Transform mode: {mode}, Shape: {params.shape}",
comments="#",
)
### Coords stuff ###
def add_coords(self, pos, event):
"""Responds to a click on an image. Redraws the images after the click. Also saves the click location in a file."""
i = self.slice_num.get()
if pos == "ebsd":
scale = int(self.resize_vars["ebsd"].get()) / 100
x = int(np.around(self.ebsd.canvasx(event.x), 0))
y = int(np.around(self.ebsd.canvasy(event.y), 0))
x = int(np.around(x / scale, 0))
y = int(np.around(y / scale, 0))
else:
scale = int(self.resize_vars["bse"].get()) / 100
x = int(np.around(self.bse.canvasx(event.x), 0))
y = int(np.around(self.bse.canvasy(event.y), 0))
x = int(np.around(x / scale, 0))
y = int(np.around(y / scale, 0))
if i not in self.points[pos].keys():
self.points[pos][i] = []
try:
self.points[pos][i] = np.append(self.points[pos][i], [[x, y]], axis=0)
except ValueError:
self.points[pos][i] = np.array([[x, y]])
self.write_coords()
# path = self.points_path[pos]
# with open(path, "a", encoding="utf8") as output:
# output.write(f"{i} {x} {y}\n")
self._show_points()
def write_coords(self):
if self.points_path["ebsd"] == "" or self.points_path["bse"] == "":
return
for mode in ["ebsd", "bse"]:
path = self.points_path[mode]
data = []
pts = self.points[mode]
for key in pts.keys():
pts_temp = np.array(pts[key])
if pts_temp.size == 0:
continue
# Handle if there is only one point and give a z value for each point
if pts_temp.ndim == 1:
s = np.insert(pts_temp, 0, key).reshape(1, 3)
else:
s = np.hstack((np.ones((pts_temp.shape[0], 1)) * key, pts_temp))
data.append(s)
# Handle if there is one slice or if there are multiple slices with points
if len(data) == 0:
continue
elif len(data) > 1:
data = np.vstack(data)
else:
data = np.array(data[0])
np.savetxt(path, data, fmt="%i", delimiter=" ")
def clear_points(self, mode):
if mode == "ebsd":
self.ebsd.delete("all")
self.points["ebsd"][self.slice_num.get()] = []
elif mode == "bse":
self.bse.delete("all")
self.points["bse"][self.slice_num.get()] = []
self._update_viewers()
def remove_coords(self, pos, event):
"""Remove the point closes to the clicked location, the point should be removed from both images"""
if pos == "bse":
v = self.bse
elif pos == "ebsd":
v = self.ebsd
closest = v.find_closest(v.canvasx(event.x), v.canvasy(event.y))[0]
tag = v.itemcget(closest, "tags")
tag = tag.replace("current", "").replace("text", "").replace("bbox", "").strip()
if tag == "":
return
self.points[pos][self.slice_num.get()] = np.delete(
self.points[pos][self.slice_num.get()], int(tag), axis=0
)
path = self.points_path[pos]
with open(path, "w", encoding="utf8") as output:
for z in self.points[pos].keys():
for i in range(len(self.points[pos][z])):
if i == int(tag):
continue
x, y = self.points[pos][z][i]
output.write(f"{int(z)} {int(x)} {int(y)}\n")
self._update_viewers()
def _show_points(self):
"""Either turns on or turns off control point viewing"""
if self.show_points.get() == 1:
j = self.slice_num.get()
pc = {"ebsd": "#FEBC11", "bse": "#EF5645"}
viewers = {"ebsd": self.ebsd, "bse": self.bse}
for mode in ["ebsd", "bse"]:
scale = int(self.resize_vars[mode].get()) / 100
try:
pts = np.around(np.array(self.points[mode][j]) * scale).astype(int)
except KeyError:
continue
if pts.ndim == 1:
if pts.size == 0:
continue
pts = pts.reshape((1, 2))
for i, p in enumerate(pts):
o_item = viewers[mode].create_oval(
p[0] - 1,
p[1] - 1,
p[0] + 1,
p[1] + 1,
width=2,
outline=pc[mode],
tags=str(i),
)
t_item = viewers[mode].create_text(
p[0] + 3,
p[1] + 3,
anchor=tk.NW,
text=i,
fill=pc[mode],
font=("", 10, "bold"),
tags=str(i) + "text",
)
bbox = viewers[mode].bbox(t_item)
r_item = viewers[mode].create_rectangle(
bbox, fill="#FFFFFF", outline=pc[mode], tags=str(i) + "bbox"
)
viewers[mode].tag_raise(t_item, r_item)
else:
self.ebsd.delete("all")
self.bse.delete("all")
self._update_imgs()
### Apply stuff for visualizing ###
def _get_cropping_slice(self, centroid, target_shape, current_shape):
"""Returns a slice object that can be used to crop an image"""
rstart = centroid[0] - target_shape[0] // 2
rend = rstart + target_shape[0]
if rstart < 0:
r_slice = slice(0, target_shape[0])
elif rend > current_shape[0]:
r_slice = slice(current_shape[0] - target_shape[0], current_shape[0])
else:
r_slice = slice(rstart, rend)
cstart = centroid[1] - target_shape[1] // 2
cend = cstart + target_shape[1]
if cstart < 0:
c_slice = slice(0, target_shape[1])
elif cend > current_shape[1]:
c_slice = slice(current_shape[1] - target_shape[1], current_shape[1])
else:
c_slice = slice(cstart, cend)
return r_slice, c_slice
def _get_ebsd_path(self, volume=False):
# Set filetypes depending on image or volume data
filetypes = [
("DREAM.3D File", "*.dream3d"),
("EBSD Data", "*.ang *.h5"),
("Image Files", "*.tif *.tiff *.png *.jpg *.jpeg"),
("All files", "*.*"),
]
if volume:
filetypes.pop(1)
defaultextension = ".dream3d"
title = "Save corrected (from distorted) volume"
else:
filetypes.pop(0)
defaultextension = ".ang"
title = "Save corrected (from distorted) image"
# Ask for the EBSD path
SAVE_PATH_EBSD = filedialog.asksaveasfilename(
initialdir=os.path.basename(self.ebsd_path),
title=title,
filetypes=filetypes,
defaultextension=defaultextension,
)
# Check if the user canceled the dialog
if SAVE_PATH_EBSD == "":
return None
elif "." not in SAVE_PATH_EBSD:
raise None
# Check if the extension is valid
extension = os.path.splitext(SAVE_PATH_EBSD)[1]
if extension.lower() not in [
".jpg",
".jpeg",
".png",
".tif",
".tiff",
".h5",
".ang",
".dream3d",
]:
return None
print("Saving EBSD to:", SAVE_PATH_EBSD)
return SAVE_PATH_EBSD
def _get_mode_choice(self):
# Get the mode choice
mode = ArbitraryMessageBox(
self,
title="Mode",
msg="Select the mode to use for the correction.",
options=[
"Thin-Plate Spline",
"Thin-Plate Spline (Affine only)",
],
orientation="vertical",
)
if mode == False:
return None
else:
mode = [
"tps",
"tps affine",
][mode.choice]
print("Mode choice:", mode)
return mode
def _get_crop_choice(self):
# Ask if the user wants to crop the corrected image to match the distorted grid
crop_choice = ArbitraryMessageBox(
self,
title="Crop",
msg="Select the grid to crop the transformed output to.",
options=["Source (EBSD)", "Destination (BSE)", "None"],
)
if crop_choice == False:
return None
else:
crop_choice = ["src", "dst", "none"][crop_choice.choice]
print("Crop choice:", crop_choice)
return crop_choice
def _correct_dtype(self, data, dtype):
print("Correcting dtype", dtype, data.dtype)
# Fix integer types, leave float types as is
if data.dtype == dtype:
return data
else:
try:
# Succeeds if it tis an integer dtype
info = np.iinfo(dtype)
# Convert to 0-1 range and then scale to the max value of the dtype
data = (2**info.bits - 1) * data / data.max()
# Convert to the correct dtype
data += info.min
return np.around(data, 0).astype(dtype)
except ValueError:
# Fails if it is a float dtype
return data.astype(dtype)
def _get_dream3d_structure(self, path, data_keys):
h5 = h5py.File(path, "r")
# Get the outer key
keys_0 = list(h5.keys())
keys_0_lower = [k.lower() for k in keys_0]
key = [
keys_0[i]
for i in range(len(keys_0))
if keys_0_lower[i] not in ["datacontainerbundles", "montages", "pipeline"]
][0]
# Always only one key
key = key + f"/{list(h5[key].keys())[0]}"
# Match
keys = [key + f"/{k}" for k in h5[key].keys()]
for k in keys:
if len(h5[k].keys()) == len(data_keys):
key = k
break
h5.close()
return key
def apply_2d(self, mode="tps"):
"""Applies the correction algorithm and calls the interactive view"""
crop_choice = self._get_crop_choice()
# im0, im1 = self._run_in_background("Applying correction...", self._apply, crop_choice, mode)
im0, im1 = self._apply_2d(crop_choice, mode)
if im0 is None or im1 is None:
messagebox.showerror(
"Error",
"No points selected for the transformation. Please select points.",
)
return
if (im0.shape[0] > 2000) or (im0.shape[1] > 2000):
result = tk.messagebox.askyesnocancel(
"Resize?",
"The images are large, would you like to resize for the preview? (Recommended)",
)
if result is None:
pass
if result:
scale = int(max(im0.shape) / 2000)
im0 = im0[::scale, ::scale]