-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExM deformation analysis.py
More file actions
2056 lines (1823 loc) · 97.6 KB
/
Copy pathExM deformation analysis.py
File metadata and controls
2056 lines (1823 loc) · 97.6 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
# -*- coding: utf-8 -*-
"""
ExM deformation analysis
Created on Thu Feb 22 14:49:18 2024
Version: 27
Next goal: Try to combine mutiprocess for Calculation step
Final goal to soulve runtime ERROR(observing.....)
@author: Anchi Luo
https://github.com/AnChiLuo/Deformation-estimation-for-ExMicroscopy-Image
"""
import tkinter as tk
from tkinter.font import Font
import matplotlib
from tkinter import filedialog, ttk
from tkinter.ttk import Separator
import os
from skimage import io, exposure
from skimage.filters import threshold_otsu, gaussian
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
import pyelastix
import numpy as np
import pandas as pd
from skimage.morphology import skeletonize
from math import ceil
from matplotlib.pyplot import MultipleLocator
import threading, queue
import cv2
import subprocess
from PIL import Image, ImageTk
##Open File(Pre, Post, Skeleton)
def TextWidth(style, s, text):
# create a font object with Arial font, size 16, and bold style
font = Font(family=style, size=s)
# measure the height of the string
width = font.measure(text)
return width+200
def browseFiles_Pre():
# global Fullwidth
try :
Path_Post_ExM
FileName = filedialog.askopenfilename(initialdir = os.path.dirname(Path_Post_ExM), title = "Select a File", filetypes =[("All files", "*"),("tif files","*.tif"),("jpeg files","*.jpg"),("png files", "*.png"),("tiff files","*.tiff"),("gif files","*.gif"), ("raw files", "*.raw")])
except NameError:
FileName = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[("All files", "*"),("tiff files","*.tiff"),("jpeg files","*.jpg"),("png files", "*.png"),("tif files","*.tif"),("gif files","*.gif"), ("raw files", "*.raw")])
global Path_Pre_ExM
Path_Pre_ExM = FileName
tv_file.item(0, values=(f"{Path_Pre_ExM}",))
tv_file.tag_configure("realPath", foreground= "#ee4863")
Cur_width = tv_file.column('Path', 'width')
Fullwidth = TextWidth(Font_W, Size-2, Path_Pre_ExM)
if Fullwidth > Cur_width:
tv_file.column("Path", width= Fullwidth, stretch=0)
if 'Path_Post_ExM' in globals():
btn3.configure(state = "normal", bg = bg, fg = Color_ButNor)
btn4.configure(state = "normal", bg = bg, fg = Color_ButNor)
def browseFiles_Post():
try :
Path_Pre_ExM
FileName = filedialog.askopenfilename(initialdir = os.path.dirname(Path_Pre_ExM), title = "Select a File", filetypes =[("All files", "*"),("tif files","*.tif"),("jpeg files","*.jpg"),("png files", "*.png"),("tiff files","*.tiff"),("gif files","*.gif"), ("raw files", "*.raw")])
except NameError:
FileName = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[("All files", "*"),("jpeg files","*.jpg"),("png files", "*.png"),("tiff files","*.tiff"),("tif files","*.tif"),("gif files","*.gif"), ("raw files", "*.raw")])
global Path_Post_ExM
Path_Post_ExM = FileName
tv_file.item(1, values=(Path_Post_ExM,))
Cur_width = tv_file.column('Path', 'width')
Fullwidth = TextWidth(Font_W, Size-2, Path_Post_ExM)
if Fullwidth > Cur_width:
tv_file.column("Path", width= Fullwidth, stretch=0)
if 'Path_Pre_ExM' in globals():
btn3.configure(state = "normal", bg = bg, fg = Color_ButNor)
btn4.configure(state = "normal", bg = bg, fg = Color_ButNor)
def browseFiles_Skele():
FileName = filedialog.askopenfilename(initialdir = "/", title = "Select the Skeleton Image", filetypes =[("jpeg files","*.jpg"),("png files", "*.png"),("tiff files","*.tiff"),("tif files","*.tif"),("gif files","*.gif"),("All files", "*")])
global Path_Skeleton
Path_Skeleton = FileName
def browseFiles_Tranformix():
FileName = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[("txt files","*.txt"),("All files", "*")])
global Transformix_out
Transformix_out = FileName
tv_fileT.item(0, values = (Transformix_out,))
tv_fileT.tag_configure("realPath", foreground= "#ee4863")
Cur_width = tv_fileT.column("Path", 'width')
Fullwidth = TextWidth(Font_W, Size-2, Transformix_out)
if Fullwidth > Cur_width:
tv_fileT.column("Path", width = Fullwidth, stretch=0)
if "Transformix_out" in globals():
CheckScale2.configure(state = "normal")
Sampling_InII.configure(Act_Entry)
btnII_2.configure(Act_but)
def browseFiles_Tranformix_DF():
FileName = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[("txt files","*.txt"),("All files", "*")])
global Transformix_out_DF
Transformix_out_DF = FileName
tv_fileS2.item(1, value =(Transformix_out_DF,))
tv_fileS2.tag_configure("realPath", foreground= "#ee4863")
Cur_width = tv_fileS2.column("Path", "width")
Fullwidth = TextWidth(Font_W, Size-2, Transformix_out_DF)
if Fullwidth > Cur_width:
tv_fileS2.column("Path", width = Fullwidth, stretch = 0)
try:
Transformix_out_DF
Transformix_out_DF_fig
btnII_7.configure(Act_but)
except:
pass
def browseFiles_Tranformix_DF_fig():
FileName = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[("jpeg files","*.jpg"),("png files", "*.png"),("tiff files","*.tiff"),("tif files","*.tif"),("gif files","*.gif"),("All files", "*")])
global Transformix_out_DF_fig
Transformix_out_DF_fig = FileName
tv_fileS2.item(0, value =(Transformix_out_DF_fig,))
tv_fileS2.tag_configure("realPath", foreground= "#ee4863")
Cur_width = tv_fileS2.column("Path", "width")
Fullwidth = TextWidth(Font_W, Size-2, Transformix_out_DF_fig)
if Fullwidth > Cur_width:
tv_fileS2.column("Path", width = Fullwidth, stretch = 0)
try:
Transformix_out_DF
Transformix_out_DF_fig
btnII_7.configure(Act_but)
except:
pass
def checkDimension():
Fix = io.imread(Path_Pre_ExM)
Moving = io.imread(Path_Post_ExM)
if Fix.shape == Moving.shape:
return True
else:
tv_file.item(0, values=("The dimensions of Images are different! please select again!! "))
tv_file.item(1, values=("The dimensions of Images are different! please select again!! "))
def StartRun():
if checkDimension() == True:
def show_result(imgs,Method):
def GetName(Obj, nameLst):
N = "Composited"
for i in nameLst:
if nameLst[i] is Obj:
N = i
return N
f ,ax = plt.subplots(1,len(imgs), figsize=(20,6))
for i in range(len(imgs)):
ax[i].imshow(imgs[i], cmap = "gray")
ax[i].set_title(GetName(imgs[i], globals()))
ax[i].axis("off")
f.suptitle(Method, fontsize = 32, va = "bottom", ha = "center")
def Validate2(Num, Type):
if Num == "":
return True
else:
try :
eval(Num)
if type(eval(Num)) in Type:
return True
else:
return False
except :
return False
def ImageinPreview(Img1, Img2, Name1, Name2):
fig, ax = plt.subplots(1,2,facecolor =bg,edgecolor = "white")
ax[0].imshow(Img1, cmap = "gray")
ax[0].set_title(Name1,fontsize=18, color = "white" )
ax[0].axis("off")
ax[1].imshow(Img2, cmap = "gray")
ax[1].set_title(Name2,fontsize=18, color = "white")
ax[1].axis("off")
fig.tight_layout()
canvas_prew = FigureCanvasTkAgg(fig, master = Prev_frame1)
canvas_prew.draw()
canvas_prew.get_tk_widget().pack(side= "top", fill="both",expand=True)
def Preview():
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
Post_Img = io.imread(Path_Post_ExM, as_gray = True)
Pre_Img = io.imread(Path_Pre_ExM, as_gray = True)
if VarGau.get() == 1:
Pre_GF.set(Pre_GF_In.get())
Post_GF.set(Post_GF_In.get())
Pre_Img = gaussian(Pre_Img, sigma = Pre_GF.get())
Post_Img = gaussian(Post_Img, sigma = Post_GF.get())
ImageinPreview(Pre_Img, Post_Img, "Pre ExM", "Post ExM")
def Preview_Mask(Img1):
global M_Pre_Img
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
if VarClear.get() == 1:
M_Pre_Img = Pre_Img * Mask
ImageinPreview(Img1, M_Pre_Img, "Pre ExM", "Mask Image")
def SkeletonMaker(Img):
Thresh_Pre = threshold_otsu(Img)
Pre_binary = Img > Thresh_Pre
Pre_Skele = skeletonize(Pre_binary, method = "zhang") ##Zhang for 2d; Lee for 3D
if VarClear == 1:
Pre_Skele = Pre_Skele * Mask
return Pre_Skele
def Preview_skeleton(Img1):
global Skeleton_Img
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
if VarSkele.get() == 0:
if VarClear.get() == 1:
Img1 = Img1 * Mask
Skeleton_Img = SkeletonMaker(Img1)
elif VarSkele.get() == 1:
if "Path_Skeleton" not in globals():
browseFiles_Skele()
Skeleton_Img = io.imread(Path_Skeleton)
if VarClear.get() == 1:
Skeleton_Img = Skeleton_Img*Mask
ImageinPreview(Img1, Skeleton_Img, "Pre ExM", "Skeleton")
def checkDimension2():
global C_Post_Img
global C_Pre_Img
C_Post_Img = io.imread(Path_Post_ExM, as_gray = True)
C_Pre_Img = io.imread(Path_Pre_ExM, as_gray = True)
if C_Post_Img.shape == C_Pre_Img.shape:
global Post_Img
Post_Img = C_Post_Img
global Pre_Img
Pre_Img = C_Pre_Img
global Active_step
Active_step[0] = 2
Pre_Img = Pre_Img.astype("float32")
Post_Img= Post_Img.astype("float32")
# Step2 region activation
for widgets in frame2.winfo_children():
if widgets.winfo_class() == "Button":
if widgets.cget("text") == "Save result":
continue
widgets.configure(Act_but)
elif widgets.winfo_class() == "Frame":
for C_widgets in widgets.winfo_children():
if C_widgets.winfo_class() == "Entry":
C_widgets.configure(Act_Entry)
else:
widgets.config(state = "normal")
Pre_GF_In["state"] = "disable"
Post_GF_In["state"] = "disable"
CheckGau["state"] = "normal"
for widgets in frame1.winfo_children():
if widgets.winfo_class() == "Button":
widgets.configure(Dis_but)
btn1.config(state = "disable")
btn2.config(state = "disable")
else:
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
Error1 = tk.Label(Prev_frame1, text = "The dimensions of Images are different!\n please select again!! ", fg = "#e6d2d5",font = ("Dubai", 20), bg = bg ,relief='groove',bd = 1, padx = 100, pady = 100)
Error1.pack( anchor= "center", padx = 30, pady = 30)
def enable(Var, frame):
if Var.get() == 1:
for widgets in frame.winfo_children():
if widgets.winfo_class() == "Entry":
widgets.configure(Act_Entry)
elif widgets.winfo_class() == "Label":
widgets.configure(fg = "#2983bb", bg = bg)
elif widgets.winfo_class() == "Button":
widgets.configure(Act_but)
elif widgets.winfo_class() == "TCombobox":
widgets.config(state = "normal")
elif Var.get() == 0:
for widgets in frame.winfo_children():
if widgets.winfo_class() == "Entry":
widgets.configure(Dis_Entry)
elif widgets.winfo_class() == "Label":
widgets.configure(fg = "#2b333e", bg = bg )
elif widgets.winfo_class() == "Button":
widgets.configure(Dis_but)
elif widgets.winfo_class() == "TCombobox":
widgets.config(state = "disable")
def Composite_Img(Imgs, equalize = False):
if equalize:
Imgs = [exposure.equalize_hist(Img) for Img in Imgs]
Imgs = [Img/Img.max() for Img in Imgs]
Imgs += [np.zeros(shape = Imgs[0].shape)]
return np.dstack(Imgs)
def show_result(imgs,Method):
def GetName(Obj, nameLst):
N = "Overlay_Img"
for i in nameLst:
if nameLst[i] is Obj:
N = i
return N
fig, ax = plt.subplots(1, len(imgs), facecolor = bg, edgecolor = "white")
Color_type = ["gray", "Reds", "gray"]
for i in range(len(imgs)):
if i < 2:
Holder_img = np.zeros(imgs[i].shape + (3,))
Holder_img[:,:,i] = imgs[i]/imgs[i].max()
ax[i].imshow(Holder_img, cmap = Color_type[i])
else:
ax[i].imshow(imgs[i], cmap = Color_type[i])
ax[i].set_title(GetName(imgs[i], globals()), fontsize=18, color = "white")
ax[i].axis("off")
fig.subplots_adjust(bottom =0.05, wspace = 0.05, left = 0.02, right = 0.98, top = 0.9, hspace = 0.15)
return fig
def R_threading(func, *args):
Thred = threading.Thread(target = func, args = args)
Thred.setDaemon(True)
Thred.start()
def NR(Img1, Img2, NR_para, AS):
global Reg1st
global Info
global Active_step
Para1 = pyelastix.get_default_params(type = "SIMILARITY")
Para1.AutomaticScalesEstimation = True
Para1.NumberOfResolutions = NR_para[0]
Para1.MaximumStepLength = NR_para[1]# Stepsize too big may cause Elastix unstable and to send the images too far appart.Increasing the step length makes your program faster
Para1.MaximumNumberOfIterations = NR_para[2]
# Rigid transformation_Regist
Reg1st, field_NR, Info = pyelastix.register(Post_Img, Pre_Img, Para1, Path_Post_ExM)
q.put(1)
def NRR(Img1, Img2, R_para, AS):
global Reg2nd
global field
Para_Def = pyelastix.get_default_params(type = "BSPLINE")
Para_Def.NumberOfResolutions = R_para[0]
Para_Def.MaximumStepLength = R_para[1]
Para_Def.MaximumNumberOfIterations = R_para[2]
Para_Adv = pyelastix.get_advanced_params()
Para = Para_Def + Para_Adv
# Non_Rigid transformation__Regist & show result
Reg2nd, field = pyelastix.register(Img2, Img1, Para, Path_Post_ExM )
q.put(1)
def GoNext(AS):
global Pre_Img
global Post_Img
global Active_step
#多線程控制
global lock
global q
try:
lock
except NameError:
lock = threading.Lock()
try:
q
except NameError:
q = queue.Queue()
lock.acquire()
Temp = Active_step
if VarGau.get() == 1:
Pre_GF.set(Pre_GF_In.get())
Post_GF.set(Post_GF_In.get())
Pre_Img = gaussian(C_Pre_Img, sigma = Pre_GF.get())
Post_Img = gaussian(C_Post_Img, sigma = Post_GF.get())
elif VarGau.get() == 0:
Post_Img = C_Post_Img.astype("float32")
Pre_Img = C_Pre_Img.astype("float32")
try:
Prev_Win.after_cancel(Refresh)
except:
pass
if AS == 2:
global NR_para
## Disable Region2
for i in [Pre_GF_In, Post_GF_In, NR_Res_In, NR_Length_In, NR_Iterations_In]:
i.config(Dis_Entry)
for j in[btn5, btn6, btn9]:
j.config(Dis_but)
CheckGau.config(state = "disable")
btn7.config(Dis_but)
btn6.config(Busy_btn)
#Start NRR
Res, Leng, Iter = NR_Res.get(), NR_Length.get(), NR_Iterations.get()
NR_para = [Res, Leng, Iter]
R_threading(NR, Pre_Img, Post_Img, NR_para, AS)
Prev_Win.after(100, Refresh)
#
elif AS == 3:
global MaPre
global R_para
##Disable Region3:
for i in ["btn9", "btn10", "btn12"]:
eval(i).config(Dis_but)
for j in [R_Res_In, R_Length_In, R_Iterations_In]:
j.config(Dis_Entry)
CheckClear.config(stat = "disable")
btn10.config(Dis_but)
btn9.config(Busy_btn)
btn12.config(Dis_but)
#Check if we need the Mask Image
if VarClear.get() == 1:
MaPre = Pre_Img * Mask
Pre_Img = Pre_Img * Mask
elif VarClear.get() == 0:
Pre_Img = C_Pre_Img.astype("float32")
#Start RR
Res, Leng, Iter = R_Res_In.get(), R_Length_In.get(), R_Iterations_In.get()
R_para = [Res, Leng, Iter]
R_threading(NRR, Pre_Img, Reg1st, R_para, AS )
Prev_Win.after(100, Refresh)
elif AS == 4:
global Skeleton_Img
global Unit
global xy_offset
global ShowState
##Disable Region4
for i in [AutoChek, RefChek, CheckScale, Unit_In]:
i.config(state = "disable")
for j in [btn15, btn16, btn14]:
j.config(Dis_but)
for k in [X_scale_In, Y_scale_In, Sampling_In]:
k.config(Dis_Entry)
btn15.config(Busy_btn)
btn16.config(Dis_but)
Sampling_size = int(Sampling_In.get())
if "Skeleton_Img" not in globals():
Preview_skeleton(Pre_Img)
if Skeleton_Img.dtype != "bool":
Skeleton_Img = Skeleton_Img > 0
if VarScale.get() == 1:
Unit = Unit_In.get()
Bin_unit.set(Unit)
elif VarScale.get() == 0:
Unit = "Pixel"
Bin_unit.set(Unit)
R_threading(CDef, Sampling_size)
Prev_Win.after(100, Refresh)
elif AS == 5:
global BL
global BW
global Deformation_Lst
BW = float(Bin_width.get())
BL = float(Total_binL.get())
Bin_width_In.config(Dis_Entry)
Total_binL_In.config(Dis_Entry)
RMS_limit_In.config(Dis_Entry)
btn18.config(Busy_btn)
btn19.config(Dis_but)
Deformation_Lst = np.array(Deformation_Lst)
Deformation_Lst = np.round(Deformation_Lst, 4 )
if VarScale.get() == 1:
Deformation_Lst_R = Deformation_Lst * float(X_scale.get())
elif VarScale.get() == 0:
Deformation_Lst_R = Deformation_Lst
R_threading(CRMS, Deformation_Lst_R)
Prev_Win.after(100, Refresh)
def GoNextII(AS):
global UnitII
global Active_step
global q
#Control threading
global lock
global SowState
try:
lock
except NameError:
lock = threading.Lock()
try:
q
except NameError:
q = queue.Queue()
def Test():
global Active_step
lock.acquire()
Active_step[1] = 7
Sampling_size = int(Sampling_InII.get())
CDef(Sampling_size)
Sampling_size = int(Sampling_InII.get())
if VarScale2.get() == 1:
UnitII.set(Unit_InII.get())
elif VarScale2.get() == 0:
UnitII.set("Pixel")
# ##Disable sheetII,region1
for i in [Unit_InII, CheckScale2]:
i.config(state = "disable")
for j in [btnII_1]:
j.configure(Dis_but)
for k in [X_scale_In, Y_scale_In, Sampling_InII]:
k.config(Dis_Entry)
btnII_2.config(Busy_btn)
R_threading(Test)
Prev_Win.after(500, RefreshII)
def GoNextII_RMS(AS):
global Active_step
global q
#Control threading
global lock
try:
lock
except NameError:
lock = threading.Lock()
try:
q
except NameError:
q = queue.Queue()
def Get_Var():
global Active_step
global BWII
global BLII
global Deformation_LstII
lock.acquire()
Active_step[1] = 8
BWII = float(Bin_widthII.get())
BLII = float(Total_binLII.get())
Deformation_LstII = np.array(Deformation_LstII)
Deformation_LstII = np.round(Deformation_LstII, 4 )
if VarScale2.get() == 1:
Deformation_Lst_R = Deformation_LstII * float(X_scale2.get())
elif VarScale2.get() == 0:
Deformation_Lst_R = Deformation_LstII
CRMS(Deformation_Lst_R )
# ##Disable sheetII,region2
Bin_width_InII.config(Dis_Entry)
Total_binL_InII.config(Dis_Entry)
RMS_limit_InII.config(Dis_Entry)
btnII_3.config(Busy_btn)
btnII_4.config(Dis_but)
#Threading start, use Get_Var() to get lock
R_threading(Get_Var)
Prev_Win.after(100, RefreshII)
def CoordinateVH(Array):
Points = len(Array)
Array_YH = np.empty((Points, Points))
for j in range(0, Points):
Array_YH[j,:] = Array
Array_YV = np.einsum("ji", Array_YH)
return Array_YH, Array_YV
def CDef(Sampling_size):
global Deformation_Lst
global Distance
global xy_offset
global Deformation_LstII
global DistanceII
Temp_Deformation_Lst =[]
if Active_step[0] == 4 and Active_step != 7:
Temp_Distance = pd.DataFrame({})
# Return the displacement
xy_offset = np.array(field)
Skele_point = np.where(Skeleton_Img == True)
Temp_Distance["Ori_X"] = Skele_point[1]
Temp_Distance["Ori_Y"] = Skele_point[0]
Temp_Distance["Offset_X"] = xy_offset[0][Skeleton_Img]
Temp_Distance["Offset_Y"] = xy_offset[1][Skeleton_Img]
Temp_Distance["Deform_X"] = Temp_Distance["Ori_X"] + Temp_Distance["Offset_X"]
Temp_Distance["Deform_Y"] = Temp_Distance["Ori_Y"] + Temp_Distance["Offset_Y"]
elif Active_step[1] == 7:
outputpoints = pd.read_table(Transformix_out, header = None, delimiter = " ")
Temp_Distance = pd.DataFrame(outputpoints)
Temp_Distance = Temp_Distance[outputpoints.columns[[10,11,22,23]]]
Temp_Distance = Temp_Distance.rename(columns = {10: "Ori_X", 11: "Ori_Y", 22: "Deform_X", 23: "Deform_Y"})
##Generate deltaX and delta Y for Ori and Deform
Ori_X = np.array(Temp_Distance["Ori_X"])
Ori_XH, Ori_XV = CoordinateVH(Ori_X)
Ori_Y = np.array(Temp_Distance["Ori_Y"])
Ori_YH, Ori_YV = CoordinateVH(Ori_Y)
Deform_X = np.array(Temp_Distance["Deform_X"])
Deform_XH, Deform_XV = CoordinateVH(Deform_X)
Deform_Y = np.array(Temp_Distance["Deform_Y"])
Deform_YH, Deform_YV = CoordinateVH(Deform_Y)
#Distance calculation
deltaOri_X = Ori_XH - Ori_XV
deltaOri_Y = Ori_YH - Ori_YV
deltaDef_X = Deform_XH- Deform_XV
deltaDef_Y = Deform_YH - Deform_YV
m_Ori = np.sqrt(np.einsum("ij,ij->ij", deltaOri_X, deltaOri_X) + np.einsum("ij,ij->ij", deltaOri_Y, deltaOri_Y))
m_Def = np.sqrt(np.einsum("ij,ij->ij", deltaDef_X, deltaDef_X) + np.einsum("ij,ij->ij", deltaDef_Y, deltaDef_Y))
m_offset = m_Def - m_Ori
##Group the Deformed_distance(m) and Difference (m'-m). The sampling size is adjustable to speed up the calculation.
m_offset_F = []
m_OriN_F = []
for i in range(1, len(m_offset)):
m_offset_F += list(np.diagonal(m_offset, offset = i))
m_OriN_F += list(np.diagonal(m_Ori, offset = i))
Temp_Deformation_Lst = [[m_OriN_F[i], m_offset_F[i]] for i in range(0, len(m_offset_F), Sampling_size)]
if Active_step[0] == 4 and Active_step[1] != 7:
Deformation_Lst = Temp_Deformation_Lst
Distance = Temp_Distance
elif Active_step[1] == 7:
Deformation_LstII = Temp_Deformation_Lst
DistanceII = Temp_Distance
q.put(1)
def CRMS(Lst):
global RMS_value
global RMS_valueII
global Bin_Lst
global Bin_LstII
Temp_Lst = []
# Bin data for calculating RMS_get the Ceiling of Distance and group it.
Lst = np.array(Lst)
if Active_step[0] == 5 and Active_step[1] !=8:
Temp_Lst = [i*BW for i in range(0,ceil(max(Lst[:,0])/BW))]
elif Active_step[1] == 8:
Temp_Lst = [i*BWII for i in range(0,ceil(max(Lst[:,0])/BWII))]
#Bin_Lst = np.linspace(0, max(Deformation_Lst[:,0]), ceil(max(Deformation_Lst[:,0])/BW))# We currently break the Difference (m'-m) into BL/BW group.
label = np.digitize(Lst[:,0], Temp_Lst)# Merge the Difference (m'-m) with Bin
Deformation_DF = np.column_stack((Lst, label))
Deformation_DF = pd.DataFrame(Deformation_DF, columns = ["m","RMS","Bin_Type"])
# Calculate the RMS of each Bin
TempRMS_value = Deformation_DF.groupby("Bin_Type").agg(list)
TempRMS_value["m"]= TempRMS_value["m"].apply(lambda x: np.array(x).mean())
TempRMS_value["RMS"] = TempRMS_value["RMS"].apply(lambda i: np.linalg.norm(np.array(i))/len(i)**0.5)
if Active_step[0] == 5 and Active_step[1] !=8:
RMS_value = TempRMS_value
Bin_Lst = Temp_Lst
elif Active_step[1] == 8:
RMS_valueII = TempRMS_value
Bin_LstII = Temp_Lst
q.put(1)
def Transformix(Path):
global Raw_trans
global cmd
def Bit_convert(Path, Old_N, New_N):
Open = os.path.join(Path, Old_N)
Save = os.path.join(Path, New_N)
Img = io.imread(Open)
Img = cv2.normalize(Img, None, 0,255, cv2.NORM_MINMAX)
Img = Img.astype(np.uint8)
io.imsave(Save, Img)
def Edit_TransPara(Path):
NewLine = []
with open(Path, "r") as file:
for Item in file:
Temp = Item.replace("mhd", "tiff")
Temp = Temp.replace("double", "float")
NewLine.append(Temp)
with open(Path, "w") as file:
for line in NewLine:
file.writelines(line)
file.close()
Parent = os.path.dirname(Path)
Path_Tp_NR = os.path.join(Parent, "NRTransformParameters.0.txt")
Path_Tp_NRR = os.path.join(Parent, "NRRTransformParameters.0.txt")
Path_Img = os.path.join(Parent, "Raw.tif")
Path_Img_NR = os.path.join(Parent, "Rigid_result.tiff")
#Save Img for Transformix
Raw = io.imread(Path)
Raw = cv2.normalize(Raw, None, 0,255, cv2.NORM_MINMAX)
Raw = Raw.astype(np.uint8)
io.imsave(Path_Img, Raw)
#Edit Trasformparameter for Transformix
Edit_TransPara(Path_Tp_NR)
Edit_TransPara(Path_Tp_NRR)
#Calling Transformix
cmd = ["transformix", "-in", Path_Img, "-out", Parent, "-tp", Path_Tp_NR]
Sup_NR = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Sup_NR.communicate()
Bit_convert(Parent, "result.tiff", "Rigid_result.tiff")
cmd = ["transformix", "-in", Path_Img_NR, "-out", Parent, "-tp", Path_Tp_NRR]
Sup_NRR = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr = subprocess.STDOUT)
Sup_NRR.communicate()
Bit_convert(Parent, "result.tiff", "NonRigid_result.tiff")
Raw_trans = io.imread(Path_Img_NR)
#Clean Datas
for i in [Path_Tp_NR, Path_Tp_NRR, Path_Img, os.path.join(Parent,"result.tiff")]:
if os.path.isfile(i):
os.remove(i)
def DFmapGenerate(AS, Img1, Img2):
global q
global lock
global DFmap
btn21.config(Busy_btn)
try:
lock
except NameError:
lock = threading.Lock()
End ="No"
def DFmapcreate():
global Active_step
global DFmap
global q
lock.acquire()
global Temp_Path
Temp_Path = os.path.join(os.path.dirname(Path_Post_ExM), "DFmap.tiff")
if VarRaw.get()==1:
Transformix(Path_Post_ExM)
Overlay = Composite_Img([Pre_Img, Raw_trans])
else:
Overlay = Composite_Img([Pre_Img, Reg1st])
Gap = Gap_DM.get()
height, weight = Img1.shape
##Use meshgrid to return coordinate matrices from coordinate vectors.
##Extract row and cloumn coordinates to which flow vector values will be add
row_coords, col_coords = np.meshgrid(np.arange(height), np.arange(weight), indexing= "ij")
DFmap = plt.figure(facecolor = bg, dpi= 600)
plt.imshow(Overlay)
plt.quiver(col_coords[::Gap,::Gap],row_coords[::Gap,::Gap], -xy_offset[0][::Gap,::Gap], xy_offset[1][::Gap,::Gap] ,color= "w", units='xy', scale=1, alpha=0.9, headwidth = 4 )
plt.axis("off")
plt.tight_layout(pad=0)
plt.savefig(Temp_Path, pad_inches=0, bbox_inches='tight', transparent=True)
q.put(1)
lock.release()
def RefreshIII():
global Timer2
End = "No"
while not q.empty():
q.get()
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
DF_title = tk.Label(Prev_frame1, text = "Deformation Vector", fg = "#d0dfe6", font = (Font_W, Size), bg = bg )
DF_title.pack(anchor= "center", expand = True, fill = "x")
canvas_prew = FigureCanvasTkAgg(DFmap, master = Prev_frame1)
canvas_prew.draw()
canvas_prew.get_tk_widget().pack(anchor = "nw",expand=False, padx = 10, pady = 20)
btn21.config(Act_but)
btn23.config(Act_but)
End = "Yes"
if End =="No":
Timer2 = Prev_Win.after(100, RefreshIII)
elif End =="Yes":
Prev_Win.after_cancel(Timer2)
R_threading(DFmapcreate)
Prev_Win.after(100, RefreshIII)
def root_change(*args):
global Active_step
if Active_step[0] == 6:
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
DF_title = tk.Label(Prev_frame1, text = "Deformation Vector", fg = "#d0dfe6", font = (Font_W, Size), bg = bg )
DF_title.pack(anchor= "center", expand = True, fill = "x")
canvas_prew = FigureCanvasTkAgg(DFmap, master = Prev_frame1)
canvas_prew.draw()
canvas_prew.get_tk_widget().pack(anchor = "nw",expand=False, padx = 10, pady = 20)
btn23.config(Act_but)
def DFmapGenerateII(AS):
global q
global lock
try:
lock
except NameError:
lock = threading.Lock()
try:
q
except NameError:
q = queue.Queue()
def Get_varII():
global Active_step
global DF_info
global DFmapII
lock.acquire()
Active_step[1] = 9
#load Grid offset
Temp= pd.read_table( Transformix_out_DF, header = None, delimiter = " ")
Temp = pd.DataFrame(Temp)
Temp = Temp[Temp.columns[[10,11,28,29]]]
Temp= Temp.rename(columns = {10: "Ori_X", 11: "Ori_Y", 28: "offset_X", 29: "offset_Y"})
####Draw vector on Image(Do not disrupt codes on this region!!We will get shit!!)
DFmapII = plt.figure(facecolor = "white")
Img1 = io.imread(Transformix_out_DF_fig)
plt.imshow(Img1)
plt.quiver(np.array(Temp["Ori_Y"]), np.array(Temp["Ori_X"]), np.array(Temp["offset_Y"]), np.array(Temp["offset_X"]), color='w', units='xy', scale=1, alpha=0.5)
plt.title('Deformation Vector')
plt.ylim(max(Temp["Ori_Y"]), min(Temp["Ori_Y"]))
plt.xlim(max(Temp["Ori_X"]), min(Temp["Ori_X"]))
plt.tick_params(axis='both', bottom=False, left = False, labelbottom = False, labelleft = False)
plt.gcf().set_dpi(600)
###End of draw figure
q.put(1)
# ##Disable sheetII,region3
btnII_10.config(Dis_but)
btnII_7.config(Busy_btn)
btnII_6.config(Dis_but)
btnII_4.config(Dis_but)
#Threading start, use Get_VarII() to get lock
R_threading(Get_varII)
Prev_Win.after(100, RefreshII)
def Refresh():
global Active_step
global End
global Timer1
global MaxM
End = "No"
while not q.empty():
try:
Finish = q.get()
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
if Finish == 1 and Active_step[0] == 2:
##Disable Region2
btn6.config(Dis_but)
##Active Region3
for k in [ btn9, btn10, btn8]:
k.config(Act_but)
for L in [R_Res_In, R_Length_In, R_Iterations_In]:
L.config(Act_Entry)
CheckClear.config(state = "normal")
##Show Info in PreviewWindow
tv1.item(0, values= [round(float(i),4) for i in Info[1:]])
##Generate plot
Massage1.destroy()
Composited_Img = Composite_Img([Pre_Img, Reg1st])
fig = show_result([Pre_Img, Reg1st, Composited_Img], "Similarity Registration")
elif Finish == 1 and Active_step[0] == 3:
##Disable Region3:
btn9.config(Dis_but)
##Active Region4:
for i in [AutoChek, RefChek, CheckScale ]:
i.config(state = "normal")
for j in [btn14, btn15, btn16, btn11]:
j.config(Act_but)
Sampling_In.config(Act_Entry)
## Generate plot
Composited_Img = Composite_Img([Pre_Img, Reg2nd])
fig = show_result([Pre_Img, Reg2nd, Composited_Img], "Beta-spline Registration")
elif Finish == 1 and Active_step[0] == 4:
##Calculate the Max for measurement M
Max = np.array(Deformation_Lst)
MaxM = ceil(max(Max[:,0])/10)*10
Total_binL.set(MaxM)
##Disable Region4:
btn15.config(Dis_but)
##Active Region5
for i in [btn18, btn19, btn17]:
i.config(Act_but)
for j in [Bin_width_In, Total_binL_In, RMS_limit_In]:
j.config(Act_Entry)
State_Info = tk.Label(Prev_frame1, text = "Deflection Calculation is done!!", bg = bg, fg = "#b598a1",font = ("Dubai", Size+12), padx = 100, pady = 100, relief= relief, bd = 1 )
State_Info.pack(anchor = "nw", expand = True, fill = "both", padx = 20, pady = (10,0) )
Active_step[0] = Active_step[0]+1
End = "Yes"
lock.release()
break
elif Finish == 1 and Active_step[0] == 5:
global RMS_plot
##Disable Region5
btn18.config(Dis_but)
##Active Region6
for i in [btn21, btn22,btn20]:
i.config(Act_but)
Gap_In.config(Act_Entry)
if VarGau.get() == 1:
Raw_use["state"] = "normal"
Raw_use.select()
#ShowImage od Preview window
X_Label = [Bin_Lst[i] if i%4 == 0 else 0 for i in range(0, len(Bin_Lst))]
fig = plt.figure(figsize=(5,4))
plt.title("RMS plot")
plt.plot(RMS_value["m"], RMS_value["RMS"], color = "dodgerblue", marker = "o", label = "RMS" )
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(100))
plt.xlabel(f"Measurement Length ({Unit})")
plt.ylabel(f"RMS Error({Unit})")
plt.xticks( X_Label , fontsize = 10)
plt.xlim(0, BL)
plt.ylim(0, float(RMS_limit.get()))
plt.legend()
RMS_plot = fig
##Prepare Main window for Treeview for RMS
MainW_tv2 = tk.LabelFrame(Prev_frame1, text = "Root Mean Square(RMS) value", fg = "#d0dfe6", font = (Font_W, Size), bg = bg )
MainW_tv2.pack(anchor = "nw", expand = True, fill = "both",pady = 10, padx = 10, side = "right")
# Treeview start
tv2 = ttk.Treeview(MainW_tv2, style="mystyle1.Treeview", height= 10)
tv2.pack(anchor = "nw", side= "left", expand = True, fill = "both", padx=5)
#Add scrolly of y direction
tv2scrolly = tk.Scrollbar(MainW_tv2, orient= "vertical", command= tv2.yview)
tv2.configure(yscrollcommand= tv2scrolly.set)
tv2scrolly.pack(side= "right", fill = "y", padx = (2,5))
# Format of column
tv2["columns"] = ["m", "RMS"]
tv2.column("#0", stretch = False, width = 35, minwidth = 30)
tv2.column("m", width = 35, minwidth = 20, anchor = "center")
tv2.column("RMS", width = 35, minwidth = 20, anchor = "center")
# Heading of column
tv2.heading("#0", text = "Bin", anchor = "center")
tv2.heading("m", text = "length(m)", anchor = "center")
tv2.heading("RMS", text = "RMS", anchor = "center")
for index, row in RMS_value.iterrows():
tv2.insert(parent="", index = "end", iid = index, text= int(index), values = [round(i, 3) for i in list(row)])
## Draw result on Preview Window
canvas_prew = FigureCanvasTkAgg(fig, master = Prev_frame1)
canvas_prew.draw()
canvas.update()
canvas_prew.get_tk_widget().pack(side= "left", fill="x",expand = True, padx = 20, pady = (5,0))
End = "Yes"
lock.release()
Active_step[0] = Active_step[0]+1
except:
break
break
#Show the Result
if End == "No":
Timer1 = Prev_Win.after(500, Refresh)
elif End == "Yes":
Prev_Win.after_cancel(Timer1)
def RefreshII():
global Active_step
global End
global Timer
global BackF
End = "No"
while not q.empty():
try:
Finish = q.get()
for widgets in Prev_frame1.winfo_children():
widgets.destroy()
if Finish == 1 and Active_step[1] ==7 :
##Calculate the Max for measurement M
MaxII = np.array(Deformation_LstII)
MaxMII = ceil(max(MaxII[:,0])/10)*10
Total_binLII.set(MaxMII)
btnII_2.config(Dis_but)
for i in [btnII_3, btnII_4]:
i.config(Act_but)
for j in [Bin_width_InII, Total_binL_InII, RMS_limit_InII]:
j.config(Act_Entry)
BackF = Active_step[1]
State_Info = tk.Label(Prev_frame1, text = "Deflection Calculation is done!!", bg = bg, fg = "#b598a1",font = ("Dubai", Size+12), padx = 100, pady = 100, relief= relief, bd = 1 )
State_Info.pack(anchor = "nw", expand = True, fill = "both", padx = 20, pady = (10,0) )
Active_step[1] = 0
End = "Yes"
lock.release()
break
elif Finish == 1 and Active_step[1] ==8 :
global RMS_plotII
btnII_3.config(Dis_but)
##Active Region6
for i in [btnII_7, btnII_8, btnII_5]:
i.config(Act_but)
BackF = Active_step[1]
#ShowImage od Preview window
X_Label = [Bin_LstII[i] if i%4 == 0 else 0 for i in range(0, len(Bin_LstII))]
fig = plt.figure(figsize=(5,4))
plt.title("RMS plot of Outpupoints")
plt.plot(RMS_valueII["m"], RMS_valueII["RMS"], color = "dodgerblue", marker = "o", label = "RMS" )
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(100))
plt.xlabel("Measurement Length ("+UnitII.get()+")")
plt.ylabel("RMS Error("+UnitII.get()+")")
plt.xticks( X_Label , fontsize = 10)
plt.xlim(0, BLII)
plt.ylim(0, float(RMS_limitII.get()))
plt.legend()
RMS_plotII = fig
##Prepare Main window for Treeview for RMS
MainW_tv2 = tk.LabelFrame(Prev_frame1, text = "Root Mean Square(RMS) value", fg = "#d0dfe6", font = (Font_W, Size), bg = bg )
MainW_tv2.pack(anchor = "nw", expand = True, fill = "both",pady = 10, padx = 10, side = "right")
# Treeview start
tv2 = ttk.Treeview(MainW_tv2, style="mystyle1.Treeview", height= 10)
tv2.pack(anchor = "nw", side= "left", expand = True, fill = "both", padx=5)