-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·1875 lines (1668 loc) · 66.2 KB
/
app.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
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 08:42:22 2020
@author: Camilo Martínez
"""
import os
import statistics
import textwrap
import tkinter as tk
from pathlib import Path
from time import sleep
from tkinter import filedialog
import matplotlib
import numpy as np
from colorama import Fore, Style
import give_console_width
import model
from utils_classes import Material, Preprocessor, TrailingFormatter
from utils_functions import (
adjust_labels,
load_img,
load_variable_from_file,
pixel_counts_to_volume_fraction,
print_interlaminar_spacing_table,
print_mechanical_properties_table,
print_table_from_dict,
train_dev_test_split,
train_dev_test_split_table,
list_of_names_to_list_of_numpy_arrays,
extract_windows_from_filenames,
k_folds,
)
# Parameters for plots
matplotlib.rcParams["font.family"] = "cmr10"
matplotlib.rcParams["axes.unicode_minus"] = False
matplotlib.rcParams.update({"font.size": 16})
# Author
AUTHOR = "Camilo Martínez M."
# Console width of the current/active console.
CONSOLE_WIDTH = give_console_width.main()
# Supported image file formats
SUPPORTED_IMAGE_FORMATS = [".png"]
class SegmentationModel:
"""Simple class to keep track of the parameters of the final segmentation model."""
def __init__(
self,
K: int,
name: str,
classes: list,
subsegment_class: tuple,
filterbank: str,
superpixel_algorithm: str,
texton_matrix: np.ndarray,
scales: dict,
windows_train: dict,
windows_dev: dict,
windows_test: dict,
training_set: dict,
development_set: dict,
test_set: dict,
algorithm_parameters: tuple = (100, 1.4, 100),
) -> None:
"""
Args:
K (int): Number of clusters (i.e, number of textons).
name (str): Name of model (default, new). Used only for console.
classes (list): Classes/labels.
subsegment_class (tuple): Class to subsegment (pearlite) and the name of the
new resulting class. Ex: (pearlite, ferrite).
filterbank (str): Name of filterbank (MR8, other).
superpixel_algorithm (str): Algorithm for superpixel generation.
texton_matrix (np.ndarray): Computed texton matrix.
scales (dict): Dictionary with the information of the scales of the loaded
micrographs.
windows_train (dict): Dictionary of training windows.
windows_dev (dict): Dictionary of development windows.
windows_test (dict): Dictionary of testing windows.
training_set (dict): Dictionary of images used for training.
development_set (dict): Dictionary of images used for development.
test_set (dict): Dictionary of images used for testing.
algorithm_parameters (tuple, optional): Parameters for the superpixel algorithm.
Defaults to (100, 1.4, 100).
"""
self.K = K
self.name = name
self.filterbank = filterbank
self.classes = np.array(classes)
self.subsegment_class = subsegment_class
self.texton_matrix = texton_matrix
self.scales = scales
self.windows_train = windows_train
self.windows_dev = windows_dev
self.windows_test = windows_test
self.training_set = training_set
self.development_set = development_set
self.test_set = test_set
self.superpixel_algorithm = superpixel_algorithm
self.algorithm_parameters = algorithm_parameters
@classmethod
def from_parameters_dict(cls, parameters: dict) -> None:
return cls(
parameters["K"],
parameters["name"],
np.array(parameters["classes"]),
parameters["subsegment_class"],
parameters["filterbank"],
parameters["superpixel_algorithm"],
parameters["texton_matrix"],
parameters["scales"],
parameters["windows_train"],
parameters["windows_dev"],
parameters["windows_test"],
parameters["training_set"],
parameters["development_set"],
parameters["test_set"],
algorithm_parameters=parameters["algorithm_parameters"],
)
def get_parameters(self) -> dict:
return {
"K": self.K,
"name": self.name,
"classes": np.array(self.classes),
"subsegment_class": self.subsegment_class,
"filterbank": self.filterbank,
"superpixel_algorithm": self.superpixel_algorithm,
"texton_matrix": self.texton_matrix,
"scales": self.scales,
"windows_train": self.windows_train,
"windows_dev": self.windows_dev,
"windows_test": self.windows_test,
"training_set": self.training_set,
"development_set": self.development_set,
"test_set": self.test_set,
"algorithm_parameters": self.algorithm_parameters,
}
def segment(
self,
img: np.ndarray,
pixel_length_scale: int,
length_scale: int,
name: str = "segmentation",
) -> None:
(
original_img,
class_matrix,
new_classes,
segmentation_pixel_counts,
) = model.segment(
img,
self.classes,
self.texton_matrix,
algorithm=self.superpixel_algorithm,
algorithm_parameters=self.algorithm_parameters,
filterbank_name=self.filterbank,
plot_original=True,
plot_superpixels=True,
subsegment_class=self.subsegment_class,
)
print("\nSegmentation:\n")
model.visualize_segmentation(
original_img,
new_classes,
class_matrix,
dpi=120,
save_png=True,
png_name=name,
)
# model.plot_image_with_ground_truth(test_img, ground_truth)
segmentation_pixel_counts = adjust_labels(segmentation_pixel_counts)
volume_fractions = pixel_counts_to_volume_fraction(
segmentation_pixel_counts,
pixel_length_scale=pixel_length_scale,
length_scale=length_scale,
img_size=original_img.shape,
)
print_table_from_dict(
data=volume_fractions,
cols=[
"Phase or morphology",
"Volume fraction [µm²]",
"Percentage area [%]",
],
title="",
format_as_percentage=[2],
)
spacings = model.calculate_interlamellar_spacing(
original_img, class_matrix, new_classes, save_plots=False, dpi=300
)
interlaminar_spacing = {
"1": {
"px": spacings[0],
"µm": spacings[0] * length_scale / pixel_length_scale,
},
"2": {
"px": spacings[1],
"µm": spacings[1] * length_scale / pixel_length_scale,
},
}
print_interlaminar_spacing_table(interlaminar_spacing)
predict = _get_str_input(
"[?] Predict mechanical properties?", ["yes", "no"], default="yes"
)
if predict == "yes":
SegmentationModel.predict_mechanical_properties(
volume_fractions, interlaminar_spacing
)
@staticmethod
def predict_mechanical_properties(volume_fractions: dict, spacings: dict) -> None:
print("\nStructure-Property Relationships:\n")
print("For plain-carbon steels:\n")
print(
textwrap.dedent(
"""
σ_y = f_α[77.7 + 59.5(%Mn) + 9.1D_α^(-0.5)] + 145.5
+ 3.5λ^(-0.5) + 478(%N)^(0.5)+ 1200(%P)
"""
)
)
print(
textwrap.dedent(
"""
σ_u = f_α[20 + 2440(%N)^0.5 + 18.5D_α] + [750(1 - f_α)]
+ 3(λ^(-0.5))(1 - f_α^(0.5)) + 92.5(%Si)
"""
)
)
print("\nFor fully pearlitic steels (M = 2(λ - t); t = 0.15λ(%C)):\n")
print("\n\tIf λ >= 0.15 µm")
print("\t\tσ_y = 308 + 0.07M^(-1)")
print("\t\tσ_u = 706 + 0.072M^(-1)) + 122(%Si)")
print("\n\tIf λ < 0.15 µm")
print("\t\tσ_y = 259 + 0.087M^(-1)")
print("\t\tσ_u = 773 + 0.058M^(-1) + 122(%Si)")
print(
textwrap.dedent(
"""
Where λ is the pearlite interlamellar spacing; f_α, the percentage of
proeutectoid ferrite; D_α, the ferrite grain size; and %Mn, %Si, %P, %N
correspond to the chemical composition of the material in question.
λ is the most influential parameter in these equations; nonetheless, the
inclusion of the other parameters can improve the prediction.
Input the parameters you want to take into account; otherwise press Enter to
leave the value at zero.
"""
)
)
if (
"Proeutectoid ferrite" in volume_fractions
and volume_fractions["Proeutectoid ferrite"]["percentage area"] <= 0.1
): # pearlitic steel
p_C = _get_simple_numerical_entry("[?] %C", "float")
p_Si = _get_simple_numerical_entry("[?] %Si", "float", default_value=0)
steels = {}
for method in spacings:
steels[method] = Material(
fa=volume_fractions.get("Proeutectoid ferrite", {}).get(
"percentage area", 0
),
S_0=spacings[method]["µm"],
p_C=p_C,
p_Si=p_Si,
)
else: # plain-carbon steel
p_C = _get_simple_numerical_entry("[?] %C", "float")
p_Mn = _get_simple_numerical_entry("[?] %Mn", "float", default_value=0)
D_a = _get_simple_numerical_entry("[?] D_α, µm", "float", default_value=0)
p_N = _get_simple_numerical_entry("[?] %N", "float", default_value=0)
p_P = _get_simple_numerical_entry("[?] %P", "float", default_value=0)
p_Si = _get_simple_numerical_entry("[?] %Si", "float", default_value=0)
steels = {}
for method in spacings:
steels[method] = Material(
fa=volume_fractions["Proeutectoid ferrite"]["percentage area"],
S_0=spacings[method]["µm"],
p_C=p_C,
p_Mn=p_Mn,
D_a=D_a,
p_N=p_N,
p_P=p_P,
p_Si=p_Si,
)
mechanical_properties = {}
for method, steel in steels.items():
mechanical_properties[method] = {
"Yield Strength [MPa]": steel.sigma_y,
"Tensile Strength [MPa]": steel.sigma_u,
}
print_mechanical_properties_table(mechanical_properties, spacings)
def evaluate_classification_performance(self) -> None:
classification_metrics = model.evaluate_classification_performance(
self.K,
self.classes,
self.texton_matrix,
self.filterbank,
self.windows_train,
self.windows_dev,
self.windows_test,
save_png=False,
save_xlsx=False,
)
SegmentationModel.show_metrics(classification_metrics)
def evaluate_segmentation_performance(
self,
ground_truth: dict,
only: list = [],
return_stats: bool = False,
verbose: bool = True,
) -> dict:
segmentation_metrics = {}
jaccard_per_img = {}
for _set_name, _set in [
("Train", self.training_set),
("Dev", self.development_set),
("Test", self.test_set),
]:
if only and _set_name not in only:
continue
if verbose:
if _set_name == "Train":
print("\n[+] On Training set...")
elif _set_name == "Dev":
print("\n[+] On Development set...")
else:
print("\n[+] On Test set...")
(
segmentation_metrics[_set_name],
jaccard_per_img[_set_name],
) = model.evaluate_segmentation_performance(
_set,
ground_truth,
self.classes,
self.K,
self.texton_matrix,
self.superpixel_algorithm,
self.algorithm_parameters,
filterbank_name=self.filterbank,
verbose=verbose,
save_png=False,
save_xlsx=False,
)
for _set in jaccard_per_img:
micro_jaccard = []
for img in jaccard_per_img[_set]:
micro_jaccard.append(jaccard_per_img[_set][img]["Micro"])
segmentation_metrics[_set]["Overall Statistics"][
"Micro Averaged Jaccard Index"
] = statistics.mean(micro_jaccard)
if verbose:
SegmentationModel.show_metrics(segmentation_metrics)
if return_stats:
return segmentation_metrics
@staticmethod
def show_metrics(metrics: dict) -> None:
print("\n[+] Metrics:")
overall_stats = [
"F1 Macro",
"Overall Accuracy",
"Overall Jaccard Index",
]
if (
"Micro Averaged Jaccard Index"
in metrics[list(metrics.keys())[0]]["Overall Statistics"].keys()
):
overall_stats += ["Micro Averaged Jaccard Index"]
class_stats = [
"Accuracy",
"Recall/Sensitivity",
"Specificity",
"Precision",
"Averaged F1",
]
branch = " │ "
kf = TrailingFormatter()
for i, _set in enumerate(metrics):
if i == len(metrics) - 1:
bullet = " └── "
else:
bullet = " ├── "
print(bullet + _set + ":")
if _set != "Test":
print(f"{branch}", end="")
print("\t ├── Overall:")
for j, stat in enumerate(overall_stats):
if j == len(overall_stats) - 1:
bullet = " └── "
else:
bullet = " ├── "
value = metrics[_set]["Overall Statistics"][stat]
if _set != "Test":
print(f"{branch}", end="")
if type(value) is tuple:
value_to_print = (round(value[0], 3), round(value[1], 3))
value_to_print = str(value_to_print)
else:
value_to_print = str(round(value, 3))
print(f"\t{branch}\t{bullet}", end="")
print(kf.format("{:t:<22} {}", stat, value_to_print))
if _set != "Test":
print(f"{branch}\t{branch}\n{branch}", end="")
else:
print(f"\t{branch}\n", end="")
print(f"\t{bullet}Per Class:")
for k, stat in enumerate(class_stats):
if k == len(class_stats) - 1:
bullet = " └── "
else:
bullet = " ├── "
if _set != "Test":
print(f"{branch}", end="")
print(f"\t\t{bullet}{stat}: ", end="")
value = metrics[_set]["Class Statistics"][stat]
if type(value) is dict:
print()
for l, pair in enumerate(value.items()):
if l == len(value) - 1:
bullet = " └── "
else:
bullet = " ├── "
label, subvalue = pair
if _set != "Test":
print(f"{branch}", end="")
print(f"\t\t{branch}\t{bullet}", end="")
print(kf.format("{:t:<22} {}", label, round(subvalue, 3)))
elif type(value) is tuple:
value = (round(value[0], 3), round(value[1], 3))
print(f"{value}")
else:
print(f"{round(value, 3)}")
def _clear() -> None:
"""Clears the console."""
if os.name == "nt":
_ = os.system("cls") # For windows.
else:
_ = os.system("clear") # For mac and linux (here, os.name is 'posix').
def path_leaf(path: str) -> str:
"""Gets the filename associated with a path."""
return Path(path).stem
def _create_title(title: str) -> None:
"""Creates a proper title.
Args:
title (str): Title of the program.
"""
print("~" * CONSOLE_WIDTH + "\n")
print(_center_wrap(title, cwidth=80, width=50) + "\n")
print(" " * (CONSOLE_WIDTH - len(AUTHOR)) + AUTHOR)
print("~" * CONSOLE_WIDTH)
print("")
def _get_simple_numerical_entry(
msg: str,
type_value: str,
sign: str = "+",
default_value=None,
return_None: bool = False,
) -> float:
"""Gets an entry from the user and parses it to int or float depending on type_value parameter.
Args:
msg (str): Message to be shown before the user inputs a value.
type_value (str): int or float.
sign (str): '+' if a positive non-zero value is to be expected. '-' otherwise.
default_value (optional): Default value of variable. Defaults to None.
return_None (bool, optional): True if the value can be None. Defaults to False.
Returns:
float, int: Entry made by the user.
"""
complete_msg = msg
if default_value is not None:
complete_msg += " (Default=" + str(default_value) + ")"
complete_msg += " > "
entry_str = ""
entry = None
try:
entry_str = input(complete_msg)
if entry_str.strip() == "":
if return_None:
entry = default_value
else:
if default_value is not None:
entry = default_value
elif entry_str.strip() == "":
raise Exception("Empty string")
else:
if type_value == "float":
entry = float(entry_str.strip())
elif type_value == "int":
entry = int(entry_str.strip())
if entry <= 0 and sign == "+" and default_value != 0:
raise Exception("Expected a positive non-zero value.")
except:
# Recursion till entry receives a valid value.
entry = _get_simple_numerical_entry(msg, type_value, sign, default_value)
return entry
def _get_str_input(msg: str, valid_inputs: list, default: str = None) -> str:
complete_msg = msg + " (" + str(valid_inputs)[1:-1]
if default is not None:
complete_msg += ", Default: '" + default + "'"
complete_msg += ") > "
raw_str = input(complete_msg)
if raw_str.strip() == "" and default is not None:
return default
if raw_str.strip().lower() not in valid_inputs:
error_message = (
"[*] Invalid entry. Expected any of: "
+ str(valid_inputs)
+ " and got: "
+ raw_str
)
print(error_message + ".")
raw_str = _get_str_input(msg, valid_inputs, default)
return raw_str.strip().lower()
def _get_folder() -> str:
"""Print a numbered list of the subfolders in the working directory (i.e. the
directory the script is run from), and returns the directory the user chooses.
Returns:
str: Path of selected folder.
"""
print(
textwrap.dedent(
"""
[?] Which folder are your files located in?
If you cannot see it in this list, you need to copy the folder
containing them to the same folder as this script.
"""
)
)
dirs = [d for d in os.listdir() if os.path.isdir(d)] + ["EXIT"]
dir_dict = {ind: value for ind, value in enumerate(dirs)}
for key in dir_dict:
print("\t(" + str(key) + ") " + dir_dict[key])
while True:
try:
resp = int(input("\t> ").strip())
if resp not in dir_dict:
raise Exception("")
else:
break
except:
print("\t[*] Please, select a valid folder.")
if dir_dict[resp] == "EXIT":
return None
else:
return dir_dict[resp]
def _select_image_folder() -> str:
"""Selects the image folder by using either a GUI file chooser or a script-based
chooser.
Returns:
str: Path of image folder.
"""
try:
root = tk.Tk()
root.withdraw()
file_path = filedialog.askdirectory()
return os.path.relpath(file_path, start=os.getcwd())
except:
print("[*] Unable to open a GUI file chooser. Using script-based option.")
return _get_folder()
def _select_image(folder: str) -> str:
def _is_image(img: str) -> bool:
"""Checks if a filename or filepath is actually an image by checking its
extension. It also checks if it is a supported extension.
Args:
img (str): Filepath or filename.
Returns:
bool: True if the input filename or filepath is an image with a supported
extension.
"""
for supported_image_format in SUPPORTED_IMAGE_FORMATS:
if img.endswith(supported_image_format):
return True
return False
try:
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
return os.path.relpath(file_path, start=os.getcwd())
except:
print("[*] Unable to open a GUI file chooser. Using script-based option.")
if folder is None:
print("[*] A folder of images has not been selected yet.")
print(" Showing images in current folder.\n")
path = os.getcwd()
else:
print(
textwrap.dedent(
"""
[?] Press Enter to show files in {folder}.
Include the extension when typing the image name.
"""
)
)
while True:
img_name = input("\t[?] Image name >> ").strip()
path = os.path.join(os.getcwd(), folder)
if img_name != "":
if img_name not in os.listdir(path):
print(
f"\t[*] Image {img_name} was not found in {folder}. Try "
"again."
)
else:
return os.path.relpath(
os.path.join(folder, img_name), start=os.getcwd()
)
else:
break
files = [
file
for file in os.listdir(path)
if not os.path.isdir(file) and _is_image(file)
]
files = sorted(files) + ["EXIT"]
files_dict = {ind: value for ind, value in enumerate(files)}
for key in files_dict:
print("\t(" + str(key) + ") " + files_dict[key])
while True:
try:
resp = int(input("\t> ").strip())
if resp not in files_dict:
raise Exception("")
else:
break
except:
print("\t[*] Please, select a valid file.")
if files_dict[resp] == "EXIT":
return None
else:
img_name = files_dict[resp]
return os.path.relpath(os.path.join(path, img_name), start=os.getcwd())
def _take_option(selected_stuff: tuple) -> int:
imgs_folder, img_name, selected_model, ground_truth = selected_stuff
if imgs_folder == ".":
imgs_folder = "{Current}"
while True:
try:
option = "[?] Option "
close_bracket = False
if imgs_folder is not None:
option += f"(Image Folder: {imgs_folder}"
close_bracket = True
if img_name is not None:
if not close_bracket:
option += "("
else:
option += ", "
option += f"Image: {img_name}"
close_bracket = True
if selected_model is not None:
if not close_bracket:
option += "("
else:
option += ", "
option += f"Model: {selected_model.name}"
close_bracket = True
if ground_truth is not None:
if not close_bracket:
option += "("
else:
option += ", "
option += "Ground truth: Loaded"
close_bracket = True
if close_bracket:
option += ")"
option += " >> "
selected_option = int(input(option).strip())
return selected_option
except:
print("[*] Select a valid option.")
def _take_tool_option(selected_stuff: tuple) -> int:
(
labeled_folder,
preprocessed_folder,
) = selected_stuff
while True:
try:
option = "[?] Option "
close_bracket = False
for variable_name, variable in [
("Folder of labeled images", labeled_folder),
("Folder of preprocessed images", preprocessed_folder),
]:
if variable is not None:
if not close_bracket:
option += "("
else:
option += ", "
option += f"{variable_name}: {variable}"
close_bracket = True
if close_bracket:
option += ")"
option += " >> "
selected_option = int(input(option).strip())
return selected_option
except:
print("[*] Select a valid option.")
def _center_wrap(text: str, cwidth: int = 80, **kw) -> str:
"""Centers a text.
Args:
text (str): Text to center.
cwidth (int): Wanted width. Defaults to 80.
**kw: Arguments of textwrap.wrap
Returns:
str: Centered text.
"""
lines = textwrap.wrap(text, **kw)
return "\n".join(line.center(cwidth) for line in lines)
def _load_default_feature_vectors() -> dict:
return load_variable_from_file("feature_vectors", "saved_variables")
def _load_default_parameters() -> dict:
parameters = {
"K": 6,
"filterbank": "MR8",
"name": "Default",
"classes": ["proeutectoid ferrite", "pearlite"],
"subsegment_class": ("pearlite", "ferrite"),
"superpixel_algorithm": "felzenszwalb",
"algorithm_parameters": (100, 1.4, 100),
"texton_matrix": None,
"scales": None,
"windows_train": None,
"windows_dev": None,
"windows_test": None,
"training_set": None,
"development_set": None,
"test_set": None,
}
return parameters
def _load_new_parameters() -> dict:
K = _get_simple_numerical_entry("[?] Define K", "int", default_value=6)
filterbank = _get_str_input("[?] Filterbank", ["MR8", "MAT"], default="MR8")
superpixel_algorithm = _get_str_input(
"[?] Superpixel algorithm",
["quickshift", "slic", "felzenszwalb", "watershed"],
default="felzenszwalb",
)
if superpixel_algorithm == "slic":
n_segments = _get_simple_numerical_entry(
"├── [?] Number of centers for K-Means, n_segments",
"int",
default_value=500,
)
sigma = _get_simple_numerical_entry(
"├── [?] Width of gaussian smoothing kernel, sigma",
"float",
default_value=0,
)
compactness = _get_simple_numerical_entry(
"└── [?] Color and space proximity balance, compactness",
"float",
default_value=0.17,
)
algorithm_parameters = (n_segments, sigma, compactness)
elif superpixel_algorithm == "felzenszwalb":
scale = _get_simple_numerical_entry(
"├── [?] Free parameter. Higher means more clusters, scale",
"float",
default_value=100,
)
sigma = _get_simple_numerical_entry(
"├── [?] Width of gaussian smoothing kernel, sigma",
"float",
default_value=1.4,
)
min_size = _get_simple_numerical_entry(
"└── [?] Minimum component size, min_size > ", "int", default_value=100
)
algorithm_parameters = (scale, sigma, min_size)
elif superpixel_algorithm == "quickshift":
ratio = _get_simple_numerical_entry(
"├── [?] Color-space and image-space proximity, ratio",
"float",
default_value=1,
)
kernel_size = _get_simple_numerical_entry(
"├── [?] Width of gaussian smoothing kernel, kernel_size",
"float",
default_value=5,
)
sigma = _get_simple_numerical_entry(
"├── [?] Scale of the local density approximation, sigma",
"float",
default_value=0,
)
max_dist = _get_simple_numerical_entry(
"└── [?] Cut-off point for data distances, max_dist",
"float",
default_value=10,
)
algorithm_parameters = (ratio, kernel_size, max_dist, sigma)
else: # superpixel_algorithm == "watershed":
markers = _get_simple_numerical_entry(
"├── [?] Desired number of markers, markers",
"int",
default_value=None,
return_None=True,
)
compactness = _get_simple_numerical_entry(
"└── [?] Compact watershed parameter, compactness", "float", default_value=0
)
algorithm_parameters = (markers, compactness)
parameters = {
"K": K,
"filterbank": filterbank,
"name": "New",
"classes": ["proeutectoid ferrite", "pearlite"],
"subsegment_class": ("pearlite", "ferrite"),
"superpixel_algorithm": superpixel_algorithm,
"algorithm_parameters": algorithm_parameters,
"texton_matrix": None,
"scales": None,
"windows_train": None,
"windows_dev": None,
"windows_test": None,
"training_set": None,
"development_set": None,
"test_set": None,
}
return parameters
def _load_default_scales_dictionary() -> dict:
return load_variable_from_file("scales", "saved_variables")
def _preprocess_folder(path: str, dst: str) -> None:
myPreprocessor = Preprocessor(path, dst)
myPreprocessor.process()
def _set_up_train_dev_test_split() -> tuple:
print("\n[?] Set up train/dev/test split. Remember train_size + dev_size <= 1")
train_size = 1
dev_size = 1
while True:
while True:
try:
train_size = float(input("[?] Train size (<= 1) > "))
if train_size > 1 or train_size <= 0:
raise Exception("")
break
except:
print("[*] Please, input a valid entry.")
while True:
try:
dev_size_str = input("[?] Dev size (<= 1) > ").strip().lower()
if dev_size_str == "over":
break
dev_size = float(dev_size_str)
if train_size + dev_size > 1 or dev_size < 0:
raise Exception("")
return train_size, dev_size
except:
print(
"[*] Please, input a valid entry. Or type 'over' if you want to "
"redefine train_size."
)
return train_size, dev_size
def _load_ground_truth(labeled_folder: str, classes: np.ndarray) -> str:
ground_truth_path = None
try:
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
ground_truth_path = os.path.relpath(file_path, start=os.getcwd())
except:
print("[*] Unable to open a GUI file chooser. Using script-based option.")
path = os.getcwd()
print(
textwrap.dedent(
"""
[?] Press Enter to show files with .tif extension in current folder.
Include the extension when typing the file name.
"""
)
)
while True:
img_name = input("\t[?] File name >> ").strip()
if img_name != "":
if img_name not in os.listdir(path):
print(
f"\t[*] File {img_name} was not found in current folder. Try again."
)
else:
ground_truth_path = os.path.relpath(
os.path.join(path, img_name), start=os.getcwd()
)
else:
break
if ground_truth_path is None:
files = [
file
for file in os.listdir(path)
if not os.path.isdir(file) and file.endswith(".tif")