-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
101 lines (79 loc) · 3.58 KB
/
main.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
import os
import numpy as np
import tensorflow as tf
#from tensorflow.keras.models import Sequential
#from tensorflow.keras import layers
from sklearn.model_selection import train_test_split
from cv2 import imread, resize
def read_dir(path):
result = []
for img in os.listdir(path):
img = imread(os.path.join(path, img))
res = resize(img, dsize=(224, 224))
result.append(list(res))
return result
def create_dataset(folder_path, info=False):
colored, normal, transparent = [], [], []
# Informativo do load
i = 0
total = len(os.listdir(folder_path))
# Iterar por cada uma das 100 pastas
# Cada pasta contem subpastas 'Colored', 'Normal' e 'Transparent'
for paste in os.listdir(folder_path):
path1 = os.path.join(folder_path, paste, "Colored")
path2 = os.path.join(folder_path, paste, "Normal")
path3 = os.path.join(folder_path, paste, "Transparent")
colored += read_dir(path1)
normal += read_dir(path2)
transparent += read_dir(path3)
# Info
i+=1
if (i % 100 == 0):
print(f"{(i/total)*100}% concluido!")
return np.array(colored), np.array(normal), np.array(transparent)
# 1 -> Colored
# 2 -> Normal
# 3 -> Transparent
def lens_dataset(folder_path="/media/work/datasets/contact-lens/orig/IIITD_Contact_Lens_Iris_DB/Cogent Scanner"):
c, n, t = create_dataset(folder_path)
features = np.concatenate((c, n, t))
labels = np.array([[1, 0, 0] for _ in range(c.shape[0])] + [[0, 1, 0] for _ in range(n.shape[0])] + [[0, 0, 1] for _ in range(t.shape[0])]) # One-Hot
return features, labels
if __name__ == "__main__":
# Carregando o dataset
features, labels = lens_dataset()
x_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=0.33, random_state=23, shuffle=True)
# f_size, l_size = len(features), len(labels) # Sao iguais, apenas para melhor leitura do codigo
# Split como indicado pela propria database
# x_train, y_train = features[0:(floor(0.5*f_size))], labels[0:(floor(0.5*l_size))]
# x_test, y_test = features[(floor(0.5*f_size)+1):], labels[(floor(0.5*f_size)+1):]
# Neural Net em si
"""
# Camada para augmentação de imagem
img_augmentation = Sequential(
[
layers.RandomRotation(factor=0.15),
layers.RandomTranslation(height_factor=0.1, width_factor=0.1),
layers.RandomFlip(),
layers.RandomContrast(factor=0.1),
],
name="img_augmentation",
)
"""
# Modelo 1 --> Soprado da documentação do keras
inputs = tf.keras.layers.Input(shape=(224,224,3))
pre_treinada_saida = inputs
neuralNet = tf.keras.applications.EfficientNetB0(weights="imagenet", input_tensor=pre_treinada_saida, include_top=False)
neuralNet.trainable = False # O modelo base nao treina
pre_treinada_saida = tf.keras.layers.GlobalAveragePooling2D()(neuralNet.output)
pre_treinada_saida = tf.keras.layers.BatchNormalization()(pre_treinada_saida)
pre_treinada_saida = tf.keras.layers.Dropout(0.2)(pre_treinada_saida)
out = tf.keras.layers.Dense(3, activation="softmax")(pre_treinada_saida) # Output
# Construção do modelo
neuralNet = tf.keras.Model(inputs, out)
#neuralNet.summary() # Resumo da rede
neuralNet.compile(loss="categorical_crossentropy",
optimizer=tf.keras.optimizers.Adam(),
metrics=["accuracy"])
neuralNet.fit(x_train, y_train, epochs=40, validation_data=(x_test, y_test), verbose=1)
neuralNet.save("./contact-lens-model-effnetb0")