-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSOFIA.py
3205 lines (2860 loc) · 184 KB
/
SOFIA.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
from tkinter import *
import numpy as np
from numpy import percentile
import os, imutils, cv2, csv, shutil
from PIL import Image, ImageTk
from PIL import Image as im
from tkinter import filedialog
import os.path
from pathlib import Path
from scipy.spatial import distance
from tqdm import tqdm
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.lines import Line2D
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from math import log10, floor, pi
import numpy.polynomial.polynomial as poly
from datetime import date
import pyocr, pyocr.builders
"""
SOFIA Size of Oxidation Feature from Image Analysis
Allows the user to load an image and quickly crop, threshold, and detect edges to isolate lines for the purpose
of measuring scale thicknesses for internal and external oxidation.
Created by Padraig Stack for ORNL
Last modified August 24, 2021
"""
today = date.today()
today.strftime("%B %d")
#Initial fonts
if today.strftime("%B %d") == "April 1":
font1 = ("Comic Sans MS", 15)
font2 = ("Comic Sans MS", 13)
else:
font1 = ("Helvetica", 16)
font2 = ("Helvetica", 14)
class MainWindow:
#Establish the main menu
def __init__(self,main_menu): ##Initial Menu
self.main_menu = main_menu
self.main_menu.title("Main Menu")
self.main_menu.configure(bg="gray69")
Label(self.main_menu, text = "Please select the following menus to use", font = font1).grid(row = 0, columnspan = 2)
self.external_oxidation_menu_btn = Button(self.main_menu, text="External Oxidation (CC Prep)", font = font1, bg="skyblue", command = self.external_oxidation_menu)
self.external_oxidation_menu_btn.grid(row = 1, column = 0)
Label(main_menu, text="This will let you calculate the shortest distance between select contours\nor prepare samples for the concavity calculator", font = font2).grid(row =1, column = 1, pady = (5,0), sticky="W")
self.concavity_menu_btn = Button(self.main_menu, text="Concavity Calculation", font = font1, bg="slate blue", command = self.concavity_menu)
self.concavity_menu_btn.grid(row = 2, column = 0)
Label(main_menu, text="This will let you find concavity of the lower line. \nCompares thicknesses at concave and concave regions", font = font2).grid(row=2, column = 1, sticky="W", pady=(5,0))
self.internal_oxidation_menu_btn = Button(self.main_menu, text="Internal Oxidation", font= font1, bg="purple2", command = self.internal_menu)
self.internal_oxidation_menu_btn.grid(row=3, column=0)
Label(main_menu, text="Prepare CSVs to measure internal oxidation\nAlso measures continuity in slices", font = font2).grid(row=3, column=1, sticky="W", pady=(5,0))
exit_messages = ["Please don't leave, there's more corrosion to analyze", "I wouldn't leave if I were you. work is much worse", "Don't leave yet -- There's corrosion around that corner", "Go ahead and leave. See if I care.", "Are you sure you want to quit this great script?",
"You want to quit? Then, thou hast lost an eighth!", "This is no message! Page intentionally left blank"]
i = np.random.randint(len(exit_messages)) #Adaptations of quit messages from DOOM, sorry if it is unprofessional
self.exit_btn = Button(self.main_menu, text="Exit Program", font= font1, bg="tomato", command = lambda: (self.main_menu.destroy(), print(exit_messages[i])))
self.exit_btn.grid(row=4, column=0, pady=(5,0))
def reset_button(self): ##Resets the menu to start again
if "cbtn" in dir(self):
self.cbtn.destroy()
del self.cbtn
if "thresh_btn" in dir(self):
self.thresh_btn.destroy()
del self.thresh_btn
if "edge_btn" in dir(self):
self.edge_btn.destroy()
del self.edge_btn
if "save_csv_btn" in dir(self):
self.save_csv_btn.destroy()
del self.save_csv_btn
if "crop_status" in dir(self):
self.crop_status.grid_remove()
del self.crop_status
if "contour_status" in dir(self):
self.contour_status.grid_remove()
del self.contour_status
if "save_name_label" in dir(self):
self.save_name_label.grid_remove()
del self.save_name_label
if "scale_ratio" in dir(self):
del self.scale_ratio
if "scale_status" in dir(self):
del self.scale_status
if "thresh_status" in dir(self):
self.thresh_status.grid_remove()
self.status_path.configure(text="There is no loaded image", font=font2)
self.status_path.update()
def external_oxidation_menu(self): ##Creates the main menu for external oxidation image analysis
self.in_or_ex = 1
self.root = Toplevel()
self.main_menu.withdraw()
self.root.title("Auto Measurement")
self.root.configure(bg="gray69")
self.root.minsize(300,300)
self.path_btn = Button(self.root, text="Please select the image you would like to use", font = font1, bg="OliveDrab1", command = self.select_image)
self.path_btn.grid(row = 0, column = 0)
self.status_path = Label(self.root, text="There is no loaded image", font = font2)
self.status_path.grid(row = 0, column = 1)
self.current_dir = os.getcwd()
self.unworked_dir = self.current_dir+"/unworkedcsv/"
check_dir = Path(self.unworked_dir)
if check_dir.exists() is False:
os.mkdir(self.unworked_dir)
os.mkdir(self.current_dir+"/workedcsv")
waiting_files = len(os.listdir(self.unworked_dir))//3
if waiting_files > 0:
self.short_dist_btn = Button(self.root, text="Calculate Shortest Distance", font = font1, bg="dodger blue", command = self.shortest_distance)
self.short_dist_btn.grid(row=6, column=0, pady=(10,0))
if waiting_files ==1:
self.calculate_status = Label(self.root, text="There is "+str(waiting_files)+" image waiting for calculations", font = font2)
self.calculate_status.grid(row =6, column = 1, sticky="W", pady=(10,0))
else:
self.calculate_status = Label(self.root, text="There are "+str(waiting_files)+" images waiting for calculations", font = font2)
self.calculate_status.grid(row =6, column = 1, sticky="W", pady=(10,0))
self.total_calculations_entry = Entry(self.root, font=font2)
self.total_calculations_entry.insert(END, "500")
self.total_calculations_entry.grid(row=7, column = 1)
self.total_calculations_label = Label(self.root, text="The above determines the number of\nshortest distance calculations performed", font=font2)
self.total_calculations_label.grid(row=8, column = 1, sticky="W")
reverse_profiles = ["Bottom to Top", "Top to Bottom", "Both", "Vertical", "All of the Above"]
self.reverse_profile = StringVar()
self.reverse_profile.set(reverse_profiles[0])
self.reverse_profile_drop = OptionMenu(self.root, self.reverse_profile, *reverse_profiles)
self.reverse_profile_drop.config(bg="deep sky blue", font=font2)
self.reverse_profile_drop.grid(row=7, column = 0)
self.reverse_status = Label(self.root, font=font2, text="The droplist determines the direction \nthe shortest distance is calculated")
self.reverse_status.grid(row=8, column =0)
reverse_drop_list = self.root.nametowidget(self.reverse_profile_drop.menuname)
reverse_drop_list.config(font=font2)
self.reset_btn = Button(self.root, text="Reset", font=font1, bg="chocolate1", command=lambda:[self.reset_button()])
self.reset_btn.grid(row=9, column=0, sticky="S", pady=10)
self.return_btn = Button(self.root, text="Return to Main Menu", font = font1, bg="peach puff", command = lambda:[self.root.destroy(), self.main_menu.deiconify()])
self.return_btn.grid(row = 9, column= 1, sticky="S", pady=10)
def concavity_menu(self): ##Uses CSV data from internal/external measurements to measure concavities of the oxide interface
self.cc_menu = Toplevel()
self.main_menu.withdraw()
self.cc_menu.title("Concavity Calculator")
self.cc_menu.configure(bg="gray69")
self.cc_menu.minsize(300,300)
return_btn = Button(self.cc_menu, text="Return to Main Menu", font = font1, bg="peach puff", command = lambda:[self.cc_menu.destroy(), self.main_menu.deiconify()])
return_btn.grid(row = 6, columnspan = 2)
csv_select = Button(self.cc_menu, text="Select CSVs", font=font1, bg="deep sky blue", command = self.load_csv)
csv_select.grid(row = 1, column = 0)
self.cc_csv_status = Label(self.cc_menu, text="Select the csv you would like to use for calculations", font=font2)
self.cc_csv_status.grid(row=1,column = 1)
def internal_menu(self): ##Creates the main menu for internal oxidation image analysis
self.in_or_ex = 0
self.root = Toplevel()
self.main_menu.withdraw()
self.root.title("Internal Oxidation")
self.root.configure(bg="gray69")
self.root.minsize(300,300)
path_btn = Button(self.root, text="Please select the image you would like to use", font = font1, bg="OliveDrab1", command = self.select_image)
path_btn.grid(row = 0, column = 0)
self.status_path = Label(self.root, text="There is no loaded image", font = font2)
self.status_path.grid(row = 0, column = 1)
self.current_dir = os.getcwd()
worked_dir = self.current_dir+"/worked-internalcsv/"
check_dir = Path(worked_dir)
if check_dir.exists() is False:
os.mkdir(worked_dir)
reset_btn = Button(self.root, text="Reset", bg="chocolate1", font=font1, command=self.reset_button)
reset_btn.grid(row=8, column=0, sticky="S", pady=10)
return_btn = Button(self.root, text="Return to Main Menu", font = font1, bg="peach puff", command = lambda:[self.root.destroy(), self.main_menu.deiconify()])
return_btn.grid(row = 8, column = 1, sticky="S", pady=10)
#Internal and External functions
#Image selection/property generation
def select_image(self): ##Allows the user to select an image to analyse
self.reset_button()
self.path = filedialog.askopenfilename(filetypes = [("Image", ".bmp"), ("Image", ".tif"), ("Image", ".jpg"), ("Image", ".png")])
if len(self.path) > 0:
self.directory = os.path.dirname(self.path)
self.filename = os.path.basename(self.path)
self.orig_img = cv2.imread(self.path, 0)
self.img_width = self.orig_img.shape[1]
self.img_height = self.orig_img.shape[0]
if self.img_width > self.img_height:
self.image_ratio = self.img_width // 1000
else:
self.image_ratio = self.img_height // 1000
if self.image_ratio == 0:
self.image_ratio = int(1)
self.scale_values()
self.center_circle = int(self.image_ratio)
self.label_text = int((self.image_ratio//2)+1)
self.scale_bar = int(round_to_1(self.img_width)/10)
image_area = self.img_width * self.img_height
self.area_thresh = int(image_area * .00004)
self.contour_buffer = int(self.image_ratio*3.125)
self.crackbuffer = int(5)
self.status_path.configure(text=("The current loaded image is: " + self.filename), font=font2)
self.status_path.update()
if "cbtn" not in dir(self):
self.cbtn = Button(self.root, text="Crop the image", bg="PaleTurquoise1", font=font1, command = self.crop_image)
self.cbtn.grid(row = 1, column = 0)
else:
self.status_path.configure(text="You have not selected a new image, please select one", font=font2)
self.status_path.update()
def scale_values(self, pct=2): ##Recallable dynamic resolution function
monitor_width = self.root.winfo_screenwidth() #Obtains screen size for scaling purposes
if pct != 2:
if pct <= 0.3:
modifier = 1
elif pct <= 0.4:
modifier = 0.8
elif pct <= 0.5:
modifier = 0.7
elif pct <= 0.6:
modifier = 0.6
else:
modifier = 0.5
else:
modifier = 1
if self.in_or_ex == 1:
if monitor_width >= 1920 and monitor_width < 2560: #Adjusts the image sizes based off monitor resolution width (assumed 16:9)
self.fullsize = int((75/self.image_ratio)*modifier)
self.crop_resize = int((135/self.image_ratio)*modifier)
self.croped_resize = int((165/self.image_ratio)*modifier)
self.contour_resize = int((140/self.image_ratio)*modifier)
self.thresh_width = int((165*self.image_ratio))
elif monitor_width < 1920:
self.fullsize = int((50/self.image_ratio)*modifier)
self.crop_resize = int((90/self.image_ratio)*modifier)
self.croped_resize = int((110/self.image_ratio)*modifier)
self.contour_resize = int((80/self.image_ratio)*modifier)
self.thresh_width = int(110*self.image_ratio)
else:
self.fullsize = int((100/self.image_ratio)*modifier)
self.crop_resize = int((180/self.image_ratio)*modifier)
self.croped_resize = int((220/self.image_ratio)*modifier)
self.contour_resize = int((160/self.image_ratio)*modifier)
self.thresh_width = int(220*self.image_ratio)
self.vertical_check = int(4*self.image_ratio)
self.edge_limit = int(25*self.image_ratio)
else:
if monitor_width >= 1920 and monitor_width < 2560: #Adjusts the image sizes based off monitor resolution width (assumed 16:9)
self.fullsize = int((70/self.image_ratio)*modifier)
self.crop_resize = int((150/self.image_ratio)*modifier)
self.croped_resize = int((150/self.image_ratio)*modifier)
self.contour_resize = int((105/self.image_ratio)*modifier)
self.thresh_width = int(150*self.image_ratio)
elif monitor_width < 1920:
self.fullsize = int((45/self.image_ratio)*modifier)
self.crop_resize = int((100/self.image_ratio)*modifier)
self.croped_resize = int((100/self.image_ratio)*modifier)
self.contour_resize = int((70/self.image_ratio)*modifier)
self.thresh_width = int(100*self.image_ratio)
else:
self.fullsize = int((90/self.image_ratio)*modifier)
self.crop_resize = int((160/self.image_ratio)*modifier)
self.croped_resize = int((200/self.image_ratio)*modifier)
self.contour_resize = int((140/self.image_ratio)*modifier)
self.thresh_width = int(200*self.image_ratio)
self.vertical_check = int(2*self.image_ratio)
self.edge_limit = int(3*self.image_ratio)
#Crop menu and scale bar determining
def crop_image(self): ##Creates a menu to crop the image. Also contains the feature to set a manual scale
if "crop_menu" in dir(self):
self.crop_menu.destroy()
if "crop_close" in dir(self):
del self.crop_close
self.crop_menu = Toplevel()
self.crop_menu.title=("Cropping Menu")
self.crop_menu.configure(bg="gray69")
self.crop_menu.minsize(300,300)
Label(self.crop_menu, text=("The image you have loaded is " +str(self.img_height) +" pixels tall"
"\nAdjust the parameters until the entire scale is in the frame"), bg="thistle1", font=font2).grid(row = 0, columnspan = 2)
orig_scale = self.orig_img.copy() #Creates a scale on the side of the image to help with cropping
for i in range(self.img_height//self.scale_bar):
cv2.putText(orig_scale, str(i*self.scale_bar), (0, (self.img_height-(i*self.scale_bar))), cv2.FONT_HERSHEY_SIMPLEX, (self.label_text+2), (255,255,255),(self.center_circle+3))
cv2.putText(orig_scale, "____", (0, (self.img_height-(i*self.scale_bar))), cv2.FONT_HERSHEY_SIMPLEX, (self.label_text+2), (255,255,255),(self.center_circle))
orig_resize = resize(orig_scale, self.fullsize) #Prepares and adds an image to the GUI
resize_width = orig_resize.shape[1]
resize_height = orig_resize.shape[0]
orig_resize = ImageTk.PhotoImage(Image.fromarray(orig_resize))
self.crop_canvas = Canvas(self.crop_menu, width=resize_width, height=resize_height)
self.crop_canvas.grid(row = 10, columnspan = 3)
self.cropping_image= self.crop_canvas.create_image(0,0, image= orig_resize, anchor=NW)
self.crop_canvas.update()
Label(self.crop_menu, text="Lower Height", font= font2).grid(row = 2, column = 0, sticky = "E") #Entry for lower height
self.lower_crop = Scale(self.crop_menu, from_=0, to=self.img_height, orient = HORIZONTAL, length=400, command= self.crop_update)
self.lower_crop.set(0)
self.lower_crop.grid(row = 2, column = 1, columnspan = 2, sticky = "W")
Label(self.crop_menu, text="Upper Height", font= font2).grid(row = 1, column = 0, sticky = "E") #Entry for upper height
self.upper_crop = Scale(self.crop_menu, from_=0, to=self.img_height, orient = HORIZONTAL, length=400, command= self.crop_update)
self.upper_crop.set(self.img_height)
self.upper_crop.grid(row = 1, column = 1, columnspan = 2, sticky = "W")
if "scale_ratio" not in dir(self):
ratio, ratio_text, bar_length = scale_reader(self.path)
if ratio == "Error":
self.scale_status = Label(self.crop_menu, text="The scale ratio was not determined automatically.\nPlease determine it using on of the buttons.Adjust crop if necessary", font=font2)
self.scale_status.grid(row = 6, column = 0, columnspan = 2)
elif ratio == "No_tool":
self.scale_status = Label(self.crop_menu, text="The scale ratio was not determined automatically. You do not have to required tools installed.\nPlease determine it using on of the buttons.Adjust crop if necessary", font=font2)
self.scale_status.grid(row = 6, column = 0, columnspan = 2)
else:
self.scale_status = Label(self.crop_menu, text="The scale ratio has been determined automatically! The scale bar text read was: "+str(ratio_text)+".\nYou can override scale length with the below entry. Adjust crop if necessary", font=font2)
self.scale_status.grid(row = 6, column = 0, columnspan = 2)
self.scale_ratio = ratio
self.OCR_override_entry = Entry(self.crop_menu, font=font2)
self.OCR_override_entry.insert(END, str(ratio_text))
self.OCR_override_entry.grid(row = 7, column = 0)
self.bar_length = bar_length
else:
self.scale_status = Label(self.crop_menu, text="The scale ratio from the previous image is currently being used.\nOverride using the other scale options. Adjust crop if necessary", font=font2)
self.scale_status.grid(row=6, column = 0, columnspan = 2)
scale_reader_redo_btn = Button(self.crop_menu, text="Redo Auto Scale Reader", bg="MediumOrchid2", font=font2, command = self.scale_reader_redo)
scale_reader_redo_btn.grid(row = 7, column = 0)
scale_reader_btn = Button(self.crop_menu, text="Scale Bar Selection", bg="lawn green", font=font2, command = lambda: self.scale_reader_manual(resize_width))
scale_reader_btn.grid(row =7, column = 1)
self.scale_manual_entry = Entry(self.crop_menu, font=font2)
self.scale_manual_entry.insert(END, "Enter the scale ratio here")
self.scale_manual_entry.grid(row = 6, column = 2, sticky="S")
self.scale_entry_btn = Button(self.crop_menu, text="Use Value in Entry (px/um)", bg="dark orange", font=font2, command = self.set_scale_manual_entry)
self.scale_entry_btn.grid(row=7, column=2)
def crop_update(self, x): ##Reads the values of the crop sliders to update the image displayed in the crop menu
self.lower_crop_val = int(float(self.img_height)-float(self.lower_crop.get()))
self.upper_crop_val = int(float(self.img_height)-float(self.upper_crop.get()))
self.crop = self.orig_img.copy()
for i in range(self.img_height//self.scale_bar):
cv2.putText(self.crop, str(i*self.scale_bar), (0, (self.img_height-(i*self.scale_bar))), cv2.FONT_HERSHEY_SIMPLEX, (self.label_text+2), (255,255,255),(self.center_circle+2))
cv2.putText(self.crop, "____", (0, (self.img_height-(i*self.scale_bar))), cv2.FONT_HERSHEY_SIMPLEX, (self.label_text+2), (255,255,255),(self.center_circle))
self.crop = self.crop[self.upper_crop_val:self.lower_crop_val, 0:self.img_width]
crop_pct = (self.lower_crop_val - self.upper_crop_val)/self.img_height
self.scale_values(crop_pct)
self.crop_resize = resize(self.crop, int((75/self.image_ratio)))
resize_width = self.crop_resize.shape[1]
resize_height = self.crop_resize.shape[0]
self.crop_canvas.config(width=resize_width, height=resize_height)
self.crop_resize = ImageTk.PhotoImage(Image.fromarray(self.crop_resize))
self.crop_canvas.itemconfigure(self.cropping_image, image=self.crop_resize)
self.crop_canvas.update()
if "crop_close" not in dir(self):
self.crop_close = Button(self.crop_menu, text = "Close and Continue", bg = "tomato", font= font2, command = self.crop_close_button)
self.crop_close.grid(row = 9, column = 1)
self.thresh_btn = Button(self.root, text="Adjust Thresholds", font = font1, bg="DeepSkyBlue2", command = self.threshold_image)
self.thresh_btn.grid(row = 2, column = 0)
self.crop_status = Label(self.root, text = "Crop has been updated", font = font1)
self.crop_status.grid(row = 1, column = 1, sticky = "W")
def crop_close_button(self):
if "OCR_override_entry" in dir(self):
self.scale_ratio = float(self.bar_length/int(self.OCR_override_entry.get()))
del self.OCR_override_entry
del self.bar_length
self.crop_menu.destroy()
def scale_reader_manual(self, resize_width): ##Manual method to determine a scale. Crops the full image to isolate the scale bar
if "scale_menu" in dir(self):
self.scale_menu.destroy()
self.crop_menu.withdraw()
self.scale_menu = Toplevel()
self.scale_menu.title=("Scale Cropping Menu")
self.scale_menu.configure(bg="gray69")
self.scale_menu.minsize(resize_width, 300)
Label(self.scale_menu, text=("Adjust the height until the scale bar is isolated"), bg="thistle1", font=font2).grid(row = 0, columnspan = 2)
orig_scale = self.orig_img.copy() #Creates a scale on the side of the image to help with cropping
orig_resize = resize(orig_scale, self.fullsize) #Prepares and adds an image to the GUI
resize_width = orig_resize.shape[1]
resize_height = orig_resize.shape[0]
orig_resize = ImageTk.PhotoImage(Image.fromarray(orig_resize))
self.scale_canvas = Canvas(self.scale_menu, width=resize_width, height=resize_height)
self.scale_canvas.grid(row = 5, column = 1, columnspan = 2, pady=5)
self.scale_crop_img = self.scale_canvas.create_image(0,0, image= orig_resize, anchor=NW)
self.scale_canvas.update()
Label(self.scale_menu, text="Lower Height", font= font2).grid(row = 2, column = 0, sticky = "E") #Entry for lower height
self.y_lower_crop = Scale(self.scale_menu, from_=0, to=self.img_height, orient = HORIZONTAL, length=400, command= self.scale_update)
self.y_lower_crop.set(0)
self.y_lower_crop.grid(row = 2, column = 1, columnspan = 2, sticky = "W")
Label(self.scale_menu, text="Upper Height", font= font2).grid(row = 1, column = 0, sticky = "E") #Entry for upper height
self.y_upper_crop = Scale(self.scale_menu, from_=0, to=self.img_height, orient = HORIZONTAL, length=400, command= self.scale_update)
self.y_upper_crop.set(self.img_height)
self.y_upper_crop.grid(row = 1, column = 1, columnspan = 2, sticky = "W")
Label(self.scale_menu, text="Left Boundary", font= font2).grid(row = 3, column = 0, sticky = "E") #Entry for lower height
self.x_lower_crop = Scale(self.scale_menu, from_=0, to=self.img_width, orient = HORIZONTAL, length=400, command= self.scale_update)
self.x_lower_crop.set(0)
self.x_lower_crop.grid(row = 3, column = 1, columnspan = 2, sticky = "W")
Label(self.scale_menu, text="Right Boundary", font= font2).grid(row = 4, column = 0, sticky = "E") #Entry for upper height
self.x_upper_crop = Scale(self.scale_menu, from_=0, to=self.img_width, orient = HORIZONTAL, length=400, command= self.scale_update)
self.x_upper_crop.set(self.img_width)
self.x_upper_crop.grid(row = 4, column = 1, columnspan = 2, sticky = "W")
scale_btn = Button(self.scale_menu, text="Done Cropping", bg="purple", font=font2, command = self.scale_select)
scale_btn.grid(row = 6, column = 1)
exit_btn = Button(self.scale_menu, text="Return to Crop Menu", bg="tomato", font=font2, command= lambda: (self.scale_menu.destroy(), self.crop_menu.deiconify()))
exit_btn.grid(row=6, column = 2)
def set_scale_manual_entry(self): ##Reads from an entry box to override the automatic or to avoid using the manual scale reading
if float(self.scale_manual_entry.get()) != 0:
self.scale_ratio = float(self.scale_manual_entry.get())
self.scale_status.configure(text="The scale ratio has been determined by manual entry.\nContinue to crop the image for thresholds")
self.scale_status.update()
def scale_reader_redo(self): ##If the previous image you worked with is not in the same dimmensions as the new image you can redo the automatic scale reading
ratio, ratio_text = scale_reader(self.path)
if ratio == "Error":
self.scale_status.configure(text="Scale ratio was not determined automatically. Using previous ratio.\nYou can override using an alternative method. Adjust crop if necessary")
self.scale_status.update()
else:
self.scale_status.configure(text="The scale ratio has been re-determined automatically!\nThe scale bar text read was: "+str(ratio_text)+". You can override using buttons. Adjust crop if necessary")
self.scale_status.update()
self.scale_ratio = ratio
def scale_update(self,x): ##Reads the values of the crop sliders to help measure the scale bar. Updates the image
self.scale_lower_crop_val = int(float(self.img_height)-float(self.y_lower_crop.get()))
self.scale_upper_crop_val = int(float(self.img_height)-float(self.y_upper_crop.get()))
self.scale_left_val = int(self.x_lower_crop.get())
self.scale_right_val = int(self.x_upper_crop.get())
scale_crop = self.orig_img.copy()
scale_crop = scale_crop[self.scale_upper_crop_val:self.scale_lower_crop_val, self.scale_left_val:self.scale_right_val]
scale_resize = resize(scale_crop, int((75/self.image_ratio)))
resize_width = scale_resize.shape[1]
resize_height = scale_resize.shape[0]
self.scale_canvas.config(width=resize_width, height = resize_height)
self.scale_resize = ImageTk.PhotoImage(Image.fromarray(scale_resize))
crop = self.orig_img[self.scale_upper_crop_val:self.scale_lower_crop_val, 0:self.img_width]
self.scale_canvas.itemconfigure(self.scale_crop_img, image=self.scale_resize)
self.scale_canvas.update()
def scale_select(self): ##Creates a menu to select between two threhsolds to help the computer identify the scale bar
if "scale_select_menu" in dir(self):
self.scale_select_menu.destroy()
self.scale_menu.withdraw()
self.scale_select_menu = Toplevel()
self.scale_select_menu.title("Scale Selection")
self.scale_select_menu.configure(bg="gray69")
scale_image = self.orig_img.copy()
scale_image = scale_image[self.scale_upper_crop_val:self.scale_lower_crop_val, self.scale_left_val:self.scale_right_val]
thresh_img_1 = cv2.inRange(scale_image, 200, 255)
thresh_img_2 = cv2.inRange(scale_image, 0, 50)
thresh_img_1_resize = resize(thresh_img_1, 75)
thresh_img_1_resize = ImageTk.PhotoImage(Image.fromarray(thresh_img_1_resize))
thresh_img_2_resize = resize(thresh_img_2, 75)
thresh_img_2_resize = ImageTk.PhotoImage(Image.fromarray(thresh_img_2_resize))
setting_1_btn = Button(self.scale_select_menu, image=thresh_img_1_resize, command = lambda: self.set_scale_threshold(thresh_img_1))
setting_1_btn.image = thresh_img_1_resize
setting_1_btn.grid(row =2, column = 0)
setting_2_btn = Button(self.scale_select_menu, image=thresh_img_2_resize, command = lambda: self.set_scale_threshold(thresh_img_2))
setting_2_btn.image = thresh_img_2_resize
setting_2_btn.grid(row = 3, column = 0)
if "scale_select_canvas" in dir(self):
self.scale_select_canvas.destroy()
if "set_scale_image" in dir(self):
del self.set_scale_image
self.scale_select_canvas = Canvas(self.scale_select_menu, width = scale_image.shape[1], height = scale_image.shape[0])
self.scale_select_canvas.grid(row = 4, columnspan = 2)
self.scale_select_canvas.update()
self.scale_select_canvas.bind("<Button 1>", self.click_ratio)
Label(self.scale_select_menu, text="Please click or enter the contour numbers\nof the edges of the scale bar:", font=font2).grid(row=5,column=0, sticky="E")
self.scale_contour_input = Entry(self.scale_select_menu, font=font2)
self.scale_contour_input.insert(END, "0")
self.scale_contour_input.grid(row=5,column = 1, sticky="W")
self.add_left_btn = Button(self.scale_select_menu, text="Add Contour as Left", bg="yellow", font=font2, command = self.add_left)
self.add_left_btn.grid(row =6, column = 0)
self.add_right_btn = Button(self.scale_select_menu, text="Add Contour as Right", bg="magenta2", font=font2, command = self.add_right)
self.add_right_btn.grid(row =6, column = 1)
def set_scale_threshold(self, image): ##Declares which of the two thresholds from the above menu that you want to work with for reading the scale bar
image, self.scale_contours = self.label_center(image, 1)
self.set_scale_img = ImageTk.PhotoImage(Image.fromarray(image))
if "set_scale_image" not in dir(self):
self.set_scale_image = self.scale_select_canvas.create_image(0,0, image = self.set_scale_img, anchor = NW)
self.scale_select_canvas.update()
else:
print("it tried")
self.scale_select_canvas.itemconfigure(self.set_scale_image, image = self.set_scale_img)
self.scale_select_canvas.update()
def click_ratio(self, event): ##Uses the position of your mouse in the Tkinter canvas to figure out what contours on the image are closest to your mouse click
mouse_x, mouse_y = event.x, event.y
mouse_x = mouse_x
mouse_y = mouse_y
m_array = [(mouse_x, mouse_y)]
near_contours = [(x,y) for x, y in self.click_tuple if (x in range(int(mouse_x - (self.image_ratio*20)), int(mouse_x + (self.image_ratio*20))) and y in range(int(mouse_y - (self.image_ratio*20)), int(mouse_y + (self.image_ratio*20))))]
if len(near_contours) > 0:
near_index = closest_node(m_array, near_contours)
close_point = near_contours[near_index]
contour_index = self.click_tuple.index(close_point)
contour_number = self.click_index[contour_index]
self.scale_contour_input.delete(0,"end")
self.scale_contour_input.insert(END, contour_number)
def label_center(self, threshedimage, scale = 0): ##Finds the coordinates for the first data point in all of the contours and if the area of the contour is above a certain size it will label the contour
if scale == 0:
threshedimage = cv2.copyMakeBorder(threshedimage, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
threshedimage = cv2.medianBlur(threshedimage, 5)
threshedimage = cv2.copyMakeBorder(threshedimage, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
cnts, _ = cv2.findContours(threshedimage, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
threshedimage = cv2.cvtColor(threshedimage, cv2.COLOR_GRAY2BGR)
step = 0
area_list = []
area_number = []
self.click_index = []
if "click_tuple" in dir(self):
del self.click_tuple
for cnt in cnts:
cx = cnt[0][0][0]
cy = cnt[0][0][1]
area = cv2.contourArea(cnt)
b, _, _ = (threshedimage[(cy-1),(cx)])
if b < 255:
area_list.append(area)
area_number.append(step)
if scale == 0:
area_limit = self.area_thresh
else:
area_limit = 0
if area > area_limit:
cv2.circle(threshedimage, (cx, cy), (3*self.center_circle), (255, 0, 0), -1)
if cx < (3*(threshedimage.shape[1])/4):
if cy < ((threshedimage.shape[0])/4):
cv2.putText(threshedimage, (str(step)), (cx, cy+(2*int(self.scale_bar/10))), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (0,0,120),(self.center_circle+1))
cv2.putText(threshedimage, (str(step)), (cx, cy+(2*int(self.scale_bar/10))), cv2.FONT_HERSHEY_SIMPLEX, self.center_circle, (0,255,0),self.center_circle)
else:
cv2.putText(threshedimage, (str(step)), (cx, cy), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (0,0,120),(self.center_circle+1))
cv2.putText(threshedimage, (str(step)), (cx, cy), cv2.FONT_HERSHEY_SIMPLEX, self.center_circle, (0,255,0),self.center_circle)
else:
if cy < ((threshedimage.shape[0])/4):
cv2.putText(threshedimage, (str(step)), (cx-(3*int(self.scale_bar/10)), cy+(2*int(self.scale_bar/10))), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (0,0,120),(self.center_circle+1))
cv2.putText(threshedimage, (str(step)), (cx-(3*int(self.scale_bar/10)), cy+(2*int(self.scale_bar/10))), cv2.FONT_HERSHEY_SIMPLEX, self.center_circle, (0,255,0),self.center_circle)
else:
cv2.putText(threshedimage, (str(step)), (cx-(3*int(self.scale_bar/10)), cy), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (0,0,120),(self.center_circle+1))
cv2.putText(threshedimage, (str(step)), (cx-(3*int(self.scale_bar/10)), cy), cv2.FONT_HERSHEY_SIMPLEX, self.center_circle, (0,255,0),self.center_circle)
contours_coord = (cx,cy),
if "click_tuple" not in dir(self):
self.click_tuple = (cx,cy),
else:
self.click_tuple = self.click_tuple + contours_coord
self.click_index.append(step)
else:
area_list.append(1)
area_number.append(step)
step += 1
if len(cnts) >= 10:
max_area_iter = 10
elif len(cnts) >= 7:
max_area_iter = 7
elif len(cnts) >= 5:
max_area_iter = 5
else:
max_area_iter = 1
for i in range(max_area_iter):
max_area = 1
max_number = 0
for j in range(len(area_list)):
if area_list[j] > max_area:
max_area = area_list[j]
max_number = area_number[j]
area_list[max_number] = 0
cx = cnts[max_number][0][0][0]
cy = cnts[max_number][0][0][1]
cv2.circle(threshedimage, (cx, cy), self.center_circle+1, (135, 206, 235), -1)
if cx < (3*(threshedimage.shape[1])/4):
if cy < ((threshedimage.shape[0])/4):
cv2.putText(threshedimage, (str(max_number)), (cx, cy+(2*int(self.scale_bar/10))), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (255,192,0),(self.center_circle+1))
else:
cv2.putText(threshedimage, (str(max_number)), (cx, cy), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (255,192,0),(self.center_circle+1))
else:
if cy < ((threshedimage.shape[0])/4):
cv2.putText(threshedimage, (str(max_number)), (cx-(3*int(self.scale_bar/10)), cy+(2*int(self.scale_bar/10))), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (255,192,0),(self.center_circle+1))
else:
cv2.putText(threshedimage, (str(max_number)), (cx-(3*int(self.scale_bar/10)), cy), cv2.FONT_HERSHEY_SIMPLEX, (self.center_circle), (255,192,0),(self.center_circle+1))
return threshedimage, cnts
def add_left(self): ##Used in the manual scale reader to determine the left side of the scale
n_contour = self.scale_contours[int(self.scale_contour_input.get())]
for d in range(len(n_contour)):
XY_Coordinates = n_contour[d]
currentx = int(XY_Coordinates[0][0])
if "scale_leftmost" not in dir(self):
self.scale_leftmost = currentx
if currentx < self.scale_leftmost:
self.scale_leftmost = currentx
if ("scale_leftmost" in dir(self)) and ("scale_rightmost" in dir(self)):
if "scale_compute_btn" not in dir(self):
self.scale_compute_btn = Button(self.scale_select_menu, text="Calculate scale size", bg="lawn green", font=font2, command = self.scale_compute)
self.scale_compute_btn.grid(row = 8, column = 1, sticky="W")
self.scale_entry = Entry(self.scale_select_menu, font=font2)
self.scale_entry.insert(END, "INSERT SCALE VALUE")
self.scale_entry.grid(row = 8, column = 0, sticky="E")
self.scale_warning.grid_remove()
if "scale_warning" not in dir(self):
self.scale_warning = Label(self.scale_select_menu, text="You have selected a left side, please select a right side")
self.scale_warning.grid(row = 7, column = 1)
def add_right(self): ##Used in the manual scale reader to determine the right side of the scale bar
n_contour = self.scale_contours[int(self.scale_contour_input.get())]
for d in range(len(n_contour)):
XY_Coordinates = n_contour[d]
currentx = int(XY_Coordinates[0][0])
if "scale_rightmost" not in dir(self):
self.scale_rightmost = currentx
if currentx > self.scale_rightmost:
self.scale_rightmost = currentx
if ("scale_leftmost" in dir(self)) and ("scale_rightmost" in dir(self)):
if "scale_compute_btn" not in dir(self):
self.scale_compute_btn = Button(self.scale_select_menu, text="Calculate scale size", bg="lawn green", font=font2, command = self.scale_compute)
self.scale_compute_btn.grid(row = 8, column = 1, sticky="W")
self.scale_entry = Entry(self.scale_select_menu, font=font2)
self.scale_entry.insert(END, "INSERT SCALE VALUE")
self.scale_entry.grid(row = 8, column = 0, sticky="E")
self.scale_warning.grid_remove()
if "scale_warning" not in dir(self):
self.scale_warning = Label(self.scale_select_menu, text="You have selected a right side, please select a left side")
self.scale_warning.grid(row = 7, column = 1)
def scale_compute(self): ##Measures the pixel length of the scale bar and divides it by the real length
if int(self.scale_entry.get()) != 0:
self.scale_ratio = float((self.scale_rightmost - self.scale_leftmost) / int(self.scale_entry.get()))
Label(self.scale_select_menu, text="Ratio has been saved!", font=font2).grid(row = 9, column = 1)
self.scale_status.configure(text="The scale ratio has been determined by manual cropping\nContinue to crop the image for thresholds")
self.scale_status.update()
self.scale_return_btn = Button(self.scale_select_menu, text="Return to Cropping", bg="tomato", font=font1, command=lambda:[self.scale_select_menu.destroy(), self.scale_menu.destroy(), self.crop_menu.deiconify()])
self.scale_return_btn.grid(row=10, column = 1)
self.scale_compute_btn.destroy()
del self.scale_compute_btn
del self.scale_warning
del self.scale_leftmost
del self.scale_rightmost
#Threshold settings
def threshold_image(self): ##Creates a menu to adjust the binary thresholds of the image
if "thresh_menu" in dir(self):
self.thresh_menu.destroy()
del self.thresh_close_btn
del self.thresh_add_btn
if "thresh_panel_new" in dir(self):
del self.thresh_panel_new
if "thresh_panel_old" in dir(self):
del self.thresh_panel_old
self.contour_iterations = []
self.thresh_menu = Toplevel()
self.thresh_menu.title("Threshold Menu")
self.thresh_menu.configure(bg="gray69")
Label(self.thresh_menu, text="Adjust the parameters until the desired section of the image is white\nThe following is a slice of the original image", font= font1).grid(row = 0, columnspan = 3)
self.crop = self.orig_img.copy()
self.crop = self.crop[self.upper_crop_val:self.lower_crop_val, 0:self.img_width]
adj_crop_img = self.crop[0:self.crop.shape[0],0:self.thresh_width] #Takes a slice of the cropped image to use as a reference window
adj_crop_img = resize(adj_crop_img, self.croped_resize)
adj_crop_img = ImageTk.PhotoImage(Image.fromarray(adj_crop_img))
adj_crop_image = Label(self.thresh_menu, text="Cropped Original", image = adj_crop_img)
adj_crop_image.image = adj_crop_img
adj_crop_image.grid(row=1, column=0)
Label(self.thresh_menu, text="Please select the lower threshold value", font= font2).grid(row = 3, column = 0, sticky = "E") #Entry to adjust lower threshold
self.low_slide = Scale(self.thresh_menu, from_=0, to=255, orient=HORIZONTAL, length=400, command= self.thresh_update)
self.low_slide.set(60)
self.low_slide.grid(row=3,column = 1, columnspan=2, sticky="W", pady=5)
Label(self.thresh_menu, text = "Please select the higher threshold value", font= font2).grid(row=5, column = 0, sticky = "E") #Entry to adjust upper threshold
self.up_slide = Scale(self.thresh_menu, from_=0, to=255, orient = HORIZONTAL, length=400, command= self.thresh_update)
self.up_slide.set(195)
self.up_slide.grid(row=5,column = 1, columnspan=2, sticky="W", pady=5)
thresh_compare_btn = Button(self.thresh_menu, text="Set Comparison Image", bg="OliveDrab1", font= font2, command= self.thresh_compare)
thresh_compare_btn.grid(row=7,column=1, sticky="W")
if self.in_or_ex == 0:
internal_threshold_btn = Button(self.thresh_menu, text="Set As Internal Threshold", bg="green", font=font2, command= lambda: self.set_internal_threshold(int(self.low_slide.get()),int(self.up_slide.get())))
internal_threshold_btn.grid(row = 7, column =2, sticky="W")
if "internal_threshold" not in dir(self):
self.internal_threshold_label = Label(self.thresh_menu, text="Please select internal threshold",font= font2)
self.internal_threshold_label.grid(row=8, column =2, sticky="W")
else:
self.internal_threshold_label = Label(self.thresh_menu, text=("The current settings are "+str(self.internal_threshold[0]) +","+str(self.internal_threshold[1])),font= font2)
self.internal_threshold_label.grid(row=8,column=2, sticky="W")
grayscale_img = ImageTk.PhotoImage(Image.open("Grayscale.jpg"))
grayscale_image = Label(self.thresh_menu, text="Grayscale Values", image=grayscale_img)
grayscale_image.image = grayscale_img
grayscale_image.grid(row = 10, columnspan = 3)
def thresh_update(self, x): ##Updates the thresholded image based on the positions of the slider bars
lower_thresh_val = self.low_slide.get()
upper_thresh_val = self.up_slide.get()
thresh_img = cv2.inRange(self.crop, lower_thresh_val, upper_thresh_val)
thresh_img_crop = thresh_img[0:thresh_img.shape[0], 0:self.thresh_width]
thresh_img_crop = resize(thresh_img_crop,self.croped_resize)
thresh_img_crop = ImageTk.PhotoImage(Image.fromarray(thresh_img_crop))
if "thresh_panel_new" not in dir(self): #Adds or updates an image to the threshold menu
self.thresh_panel_new = Label(self.thresh_menu, text="New Threshold", image = thresh_img_crop)
self.thresh_panel_new.image = thresh_img_crop
self.thresh_panel_new.grid(row=1, column = 1)
Label(self.thresh_menu, text="Most recent image\n("+str(lower_thresh_val)+"-"+str(upper_thresh_val)+")", font= font2).grid(row=2,column=1)
else:
self.thresh_panel_new.configure(image=thresh_img_crop)
self.thresh_panel_new.image=thresh_img_crop
Label(self.thresh_menu, text="Most recent image\n("+str(lower_thresh_val)+"-"+str(upper_thresh_val)+")", font= font2).grid(row=2,column=1)
self.lower_thresh_old = lower_thresh_val
self.upper_thresh_old = upper_thresh_val
if "thresh_close_btn" not in dir(self): #Creates a close button
self.thresh_close_btn = Button(self.thresh_menu, text="Close and Continue", bg="tomato", font= font2, command=self.thresh_menu.destroy)
self.thresh_close_btn.grid(row=9, column=1, sticky="W")
self.thresh_add_btn = Button(self.thresh_menu, text="Add Most Recent Threshold", font= font2, command = self.thresh_add)
self.thresh_add_btn.grid(row=8, column = 1, sticky="W")
if "edge_btn" not in dir(self): #Creates a button for the next menu
self.edge_btn = Button(self.root, text="Select Edges", font = font1, bg="MediumOrchid2", command=self.edge_select)
self.edge_btn.grid(row = 3, column = 0)
def thresh_compare(self): ##Allows the user to display a third image on the threshold menu to compare between two threshold profiles
thresh_img = cv2.inRange(self.crop, self.lower_thresh_old, self.upper_thresh_old)
thresh_img_crop = thresh_img[0:thresh_img.shape[0], 0:self.thresh_width]
thresh_img_crop = resize(thresh_img_crop,self.croped_resize)
thresh_img_crop = ImageTk.PhotoImage(Image.fromarray(thresh_img_crop))
if "thresh_panel_old" not in dir(self):
self.thresh_panel_old = Label(self.thresh_menu, text="New Threshold", image = thresh_img_crop)
self.thresh_panel_old.image = thresh_img_crop
self.thresh_panel_old.grid(row=1, column = 2)
Label(self.thresh_menu, text="Comparison Threshold\n("+str(self.lower_thresh_old)+"-"+str(self.upper_thresh_old)+")",font= font2).grid(row=2,column=2)
else:
self.thresh_panel_old.configure(image=thresh_img_crop)
self.thresh_panel_old.image=thresh_img_crop
Label(self.thresh_menu, text="Comparison Threshold\n("+str(self.lower_thresh_old)+"-"+str(self.upper_thresh_old)+")",font= font2).grid(row=2,column=2)
def thresh_add(self): ##Adds the most recent threshold profile to a list to be used later for edge detection
contour_set = [self.lower_thresh_old, self.upper_thresh_old]
if contour_set not in self.contour_iterations:
self.contour_iterations.append(contour_set)
if "thresh_status" not in dir(self):
self.thresh_status = Label(self.root, text="You have selected "+str(len(self.contour_iterations))+" different threshold", font= font2)
self.thresh_status.grid(row=2, column = 1, sticky="W")
else:
self.thresh_status.configure(text="You have selected "+str(len(self.contour_iterations))+" different thresholds", font= font2)
self.thresh_status.update()
def set_internal_threshold(self, lower_thresh,upper_thresh): ##Extra threshold profile for use with internal oxidation in case the material interface needs a different profile to have high contrast
self.internal_threshold = (lower_thresh, upper_thresh)
self.internal_threshold_label.configure(text=("The current settings are "+str(self.internal_threshold[0]) +","+str(self.internal_threshold[1])))
self.internal_threshold_label.update()
#Contour selection
def edge_select(self): ##Creates a menu to select threshold profiles for contour selection
if "edge menu" in dir(self):
self.edge_menu.destroy()
if "lower_list_0" in dir(self):
del self.lower_list_0
self.tracing_img_main = cv2.cvtColor(self.crop, cv2.COLOR_GRAY2BGR)
self.tracing_img_main = cv2.copyMakeBorder(self.tracing_img_main, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
self.tracing_img_main = cv2.copyMakeBorder(self.tracing_img_main, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
self.tracing_img_main_backup = self.tracing_img_main
self.edge_menu = Toplevel()
self.edge_menu.title("Edge Selection")
self.edge_menu.configure(bg="gray69")
self.edge_menu.minsize(300,300)
Label(self.edge_menu, text="Click on a threshold profile you have saved to mark the boundaries of the feature\n If you are working with a multilayered system you can rename the layers using the entry",font= font1).grid(row = 0, columnspan = 3)
thresh_preview = self.crop.copy()
thresh_preview = thresh_preview[0:thresh_preview.shape[0], 0:self.thresh_width]
resize_trace_img = resize(self.tracing_img_main, self.contour_resize) #Creates a trace image that shows the data selected so far
resize_trace_img = ImageTk.PhotoImage(Image.fromarray(resize_trace_img))
self.edge_menu_trace_image = Label(self.edge_menu, text="Tracing Image", image = resize_trace_img)
self.edge_menu_trace_image.image = resize_trace_img
self.edge_menu_trace_image.grid(row=5, columnspan=3, pady=10)
if len(self.contour_iterations) > 0: #Creates up to three buttons based off the list of thresholds
thresh_preview_1 = cv2.inRange(thresh_preview, self.contour_iterations[0][0], self.contour_iterations[0][1])
thresh_preview_1 = resize(thresh_preview_1,self.croped_resize)
thresh_preview_1 = ImageTk.PhotoImage(Image.fromarray(thresh_preview_1))
btn_1 = Button(self.edge_menu, image = thresh_preview_1, command = lambda: self.add_contours(0, self.contour_iterations[0][0], self.contour_iterations[0][1], 0) )
btn_1.image = thresh_preview_1
btn_1.grid(row=3, column = 0, padx=5)
self.csvlx_0 = self.csvly_0 = self.csvux_0 = self.csvuy_0 = np.array([], dtype="int64")
Label(self.edge_menu, text=(str(self.contour_iterations[0][0])+"-"+str(self.contour_iterations[0][1]))).grid(row=4, column = 0)
if len(self.contour_iterations) > 1:
thresh_preview_2 = cv2.inRange(thresh_preview, self.contour_iterations[1][0], self.contour_iterations[1][1])
thresh_preview_2 = resize(thresh_preview_2,self.croped_resize)
thresh_preview_2 = ImageTk.PhotoImage(Image.fromarray(thresh_preview_2))
btn_2 = Button(self.edge_menu, image = thresh_preview_2, command = lambda: self.add_contours(1, self.contour_iterations[1][0], self.contour_iterations[1][1], 1) )
btn_2.image = thresh_preview_2
btn_2.grid(row=3, column = 1, padx=5)
self.csvlx_1 = self.csvly_1 = self.csvux_1 = self.csvuy_1 = np.array([], dtype="int64")
Label(self.edge_menu, text=(str(self.contour_iterations[1][0])+"-"+str(self.contour_iterations[1][1]))).grid(row=4, column = 1)
self.profile_check = IntVar()
crack_buffer = Checkbutton(self.edge_menu, text="Check to make profiles unique", font=font2, variable=self.profile_check, onvalue=1, offvalue = 0)
crack_buffer.grid(row=2, column = 0, sticky="E")
if len(self.contour_iterations) >2:
thresh_preview_3 = cv2.inRange(thresh_preview, self.contour_iterations[2][0], self.contour_iterations[2][1])
thresh_preview_3 = resize(thresh_preview_3,self.croped_resize)
thresh_preview_3 = ImageTk.PhotoImage(Image.fromarray(thresh_preview_3))
btn_3 = Button(self.edge_menu, image = thresh_preview_3, command = lambda: self.add_contours(2, self.contour_iterations[2][0], self.contour_iterations[2][1], 2) )
btn_3.image = thresh_preview_3
btn_3.grid(row=3, column = 2, padx=5)
self.csvlx_2 = self.csvly_2 = self.csvux_2 = self.csvuy_2 = np.array([], dtype="int64")
Label(self.edge_menu, text=(str(self.contour_iterations[2][0])+"-"+str(self.contour_iterations[2][1]))).grid(row=4, column = 2)
if len(self.contour_iterations) == 0: #Creates at least one button using the last settings if the list is empty
thresh_preview_0 = cv2.inRange(thresh_preview, self.lower_thresh_old, self.upper_thresh_old)
thresh_preview_0 = resize(thresh_preview_0,self.croped_resize)
thresh_preview_0 = ImageTk.PhotoImage(Image.fromarray(thresh_preview_0))
btn_0 = Button(self.edge_menu, image = thresh_preview_0, command = lambda: self.add_contours(0, self.lower_thresh_old, self.upper_thresh_old, 0) )
btn_0.image = thresh_preview_0
btn_0.grid(row=3, column = 1)
self.csvlx_0 = self.csvly_0 = self.csvux_0 = self.csvuy_0 = np.array([], dtype="int64")
Label(self.edge_menu, text=(str(self.contour_iterations[0][0])+"-"+str(self.contour_iterations[0][1]))).grid(row=4, column = 0)
if "internal_threshold" not in dir(self):
self.internal_threshold = (self.lower_thresh_old, self.upper_thresh_old)
self.trace_drop_list = []
for i in range(len(self.contour_iterations)):
self.trace_drop_list.append("Layer" + str(i+1))
if len(self.trace_drop_list) == 0:
self.trace_drop_list = ["Layer1"]
self.contour_list = StringVar()
self.contour_list.set(self.trace_drop_list[0])
else:
self.save_name_entry = Entry(self.edge_menu, font=font2)
self.save_name_entry.grid(row=1, column = 1, sticky="E")
self.save_name_entry.insert(END, "Layer Name")
self.save_name_btn = Button(self.edge_menu, text="Update Layer Name", bg="medium aquamarine", font= font2, command=self.update_csv_names)
self.save_name_btn.grid(row=1, column=2, sticky="W", pady=10)
self.contour_list = StringVar()
self.contour_list.set(self.trace_drop_list[0])
self.contour_list_drop = OptionMenu(self.edge_menu, self.contour_list, *self.trace_drop_list)
self.contour_list_drop.config(bg="light sea green", font=font2)
self.contour_list_drop.grid(row=1, column = 0, sticky="E")
self.contour_drop_list = self.edge_menu.nametowidget(self.contour_list_drop.menuname)
self.contour_drop_list.config(font=font2)
self.edge_close_btn = Button(self.edge_menu, text="Close", bg="tomato", font= font2, command=self.edge_menu.destroy)
self.edge_close_btn.grid(row=6, column = 1)
def update_csv_names(self):
entry = self.contour_list.get()
index = self.trace_drop_list.index(entry)
self.trace_drop_list[index] = str(self.save_name_entry.get())
self.contour_list_drop.destroy()
self.contour_list_drop = OptionMenu(self.edge_menu, self.contour_list, *self.trace_drop_list)
self.contour_list_drop.config(bg="light sea green", font=font2)
self.contour_list_drop.grid(row=1, column = 0, sticky="E")
self.contour_drop_list = self.edge_menu.nametowidget(self.contour_list_drop.menuname)
self.contour_drop_list.config(font=font2)
self.contour_list.set(self.trace_drop_list[index])
def add_contours(self, iteration, lower_thresh, upper_thresh, list_number): ##Creates a menu to select contours from selected threshold profile
if "contour_menu" in dir(self):
self.contour_menu.destroy()
if "undo_btn" in dir(self):
del self.undo_btn
if lower_thresh == self.internal_threshold[0] and upper_thresh == self.internal_threshold[1]:
self.internal_check = 1
self.internal_list = np.array([])
else:
self.internal_check = 0
self.contour_menu = Toplevel()
self.contour_menu.title("Contour Selection")
self.contour_menu.configure(bg="gray69")
if "lower_list_0" not in dir(self):
self.lower_list_0 = self.lower_list_1 = self.lower_list_2 = np.array([])
self.upper_list_0 = self.upper_list_1 = self.upper_list_2 = np.array([])
Label(self.contour_menu, text="Click the numbers of the contours you would like to add and the position they are for\n Yellow represents a lower boundary while magenta represents an upper boundary", font= font1).grid(row = 0, columnspan = 5)
thresh_img = cv2.inRange(self.crop, lower_thresh, upper_thresh) #Creates the thresholded image, finds the contours, labels, and adds it to the contour menu
threshed_image = cv2.cvtColor(thresh_img, cv2.COLOR_GRAY2BGR)
threshed_image = cv2.copyMakeBorder(threshed_image, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
threshed_image = cv2.medianBlur(threshed_image, 5)
threshed_image = cv2.copyMakeBorder(threshed_image, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
thresh_img, contours = self.label_center(thresh_img)
self.click_contours = contours
thresh_img = resize(thresh_img,self.contour_resize)
thresh_height, thresh_width = thresh_img.shape[0], thresh_img.shape[1]
self.thresh_img = ImageTk.PhotoImage(Image.fromarray(thresh_img))
self.thresh_canvas = Canvas(self.contour_menu, width = thresh_width, height = thresh_height)
self.thresh_canvas.grid(row=1, columnspan=6)
self.thresh_canvas_image = self.thresh_canvas.create_image(0,0, image = self.thresh_img, anchor = NW)
if "profile_check" not in dir(self) or self.profile_check.get() != 1:
resize_trace_img = resize(self.tracing_img_main, self.contour_resize) #Creates a trace image that shows the data selected so far
if list_number == 0:
self.upper_list = self.upper_list_0
self.lower_list = self.lower_list_0
elif list_number == 1:
self.upper_list = self.upper_list_1
self.lower_list = self.lower_list_1
else:
self.upper_list = self.upper_list_2
self.lower_list = self.lower_list_2
self.tracing_img_0 = self.tracing_img_main
self.tracing_img_1 = self.tracing_img_main
self.tracing_img_2 = self.tracing_img_main
else:
if self.contour_list.get() == self.trace_drop_list[0]:
self.tracing_img_0 = cv2.cvtColor(self.crop, cv2.COLOR_GRAY2BGR)
self.tracing_img_0 = cv2.copyMakeBorder(self.tracing_img_0, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
self.tracing_img_0 = cv2.copyMakeBorder(self.tracing_img_0, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
resize_trace_img = resize(self.tracing_img_0, self.contour_resize)
self.upper_list = self.upper_list_0
self.lower_list = self.lower_list_0
elif self.contour_list.get() == self.trace_drop_list[1]:
self.tracing_img_1 = cv2.cvtColor(self.crop, cv2.COLOR_GRAY2BGR)
self.tracing_img_1 = cv2.copyMakeBorder(self.tracing_img_1, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
self.tracing_img_1 = cv2.copyMakeBorder(self.tracing_img_1, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
resize_trace_img = resize(self.tracing_img_1, self.contour_resize)
self.upper_list = self.upper_list_1
self.lower_list = self.lower_list_1
elif self.contour_list.get() == self.trace_drop_list[2]:
self.tracing_img_2 = cv2.cvtColor(self.crop, cv2.COLOR_GRAY2BGR)
self.tracing_img_2 = cv2.copyMakeBorder(self.tracing_img_2, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
self.tracing_img_2 = cv2.copyMakeBorder(self.tracing_img_2, 5,5,5,5, cv2.BORDER_CONSTANT, value=0)
resize_trace_img = resize(self.tracing_img_2, self.contour_resize)
self.upper_list = self.upper_list_2
self.lower_list = self.lower_list_2