-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathloading_smic.py
181 lines (132 loc) · 5.33 KB
/
loading_smic.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
import numpy as np
import sys
import math
import operator
import csv
import glob,os
import xlrd
import cv2
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from collections import Counter
from sklearn.metrics import confusion_matrix
import scipy.io as sio
import pydot, graphviz
from keras.models import Sequential, Model
from keras.layers import LSTM, Dense, TimeDistributed
from keras.utils import np_utils, plot_model
from keras import metrics
from keras import backend as K
from keras.models import model_from_json
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D
from keras.preprocessing.sequence import pad_sequences
from keras import optimizers
from keras.applications.vgg16 import VGG16 as keras_vgg16
import keras
from labelling import collectinglabel
from reordering import readinput
from evaluationmatrix import fpr
from utilities import Read_Input_Images, get_subfolders_num, data_loader_with_LOSO, label_matching, duplicate_channel
from utilities import record_scores
from models import VGG_16
def loading_labels(root_db_path, dB, databaseType):
label_filename = "SMIC_label.xlsx"
label_path = root_db_path + dB + "/" + label_filename
label_file = pd.read_excel(label_path)
label_file = label_file.dropna()
subject = label_file[['Subject']]
filename = label_file[['Filename']]
label = label_file[['Label']]
num_frames = label_file[['Frames']]
# print(label_file)
return subject, filename, label, num_frames
def Read_SMIC_Images(inputDir, listOfIgnoredSamples, dB, resizedFlag, table, workplace, spatial_size):
r = w = spatial_size
SubperdB = []
for sub in sorted([ int(infile[1:]) for infile in os.listdir(inputDir) ]):
sub_str = "s" + str(sub)
VidperSub = []
for type_me in sorted([ inrfile for inrfile in os.listdir(inputDir + sub_str + "/micro/") ]):
for vids in sorted([ video for video in os.listdir(inputDir + sub_str + "/micro/" + type_me + "/") ]):
first_frame = True
for item in sorted([image for image in os.listdir(inputDir + sub_str + "/micro/" + type_me + "/" + vids + "/")]):
item = inputDir + sub_str + "/micro/" + type_me + "/" + vids + "/" + item
img = cv2.imread(item)
[_, _, dim] = img.shape
if dim == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if resizedFlag == 1:
img = cv2.resize(img, (r, w))
if first_frame:
FrameperVid = img.flatten()
else:
FrameperVid = np.vstack(( FrameperVid, img.flatten() ))
first_frame = False
VidperSub.append(FrameperVid)
# the label in xcel is not the same as in the path
if sub < 10:
vids = vids[:1] + "0" + vids[1:]
collectinglabel(table, sub, vids, workplace + "Classification/", dB)
SubperdB.append(VidperSub)
return SubperdB
############################## Loading Labels & Images ##############################
root_db_path = "/media/ice/OS/Datasets/"
dB = "SMIC"
databaseType = ["HS", "NIR", "VIS"]
inputDir = root_db_path + dB + "/SMIC_all_cropped/" + databaseType[0] + "/"
workplace = root_db_path + dB + "/"
subject, filename, label, num_frames = loading_labels(root_db_path, dB, databaseType)
filename = filename.as_matrix()
label = label.as_matrix()
table = np.transpose( np.array( [filename, label] ) )
# os.remove(workplace + "Classification/SMIC_label.txt")
################# Variables #############################
spatial_size = 224
r = w = spatial_size
subjects=26
# subjects=2
samples = 246
n_exp = 5
IgnoredSamples_index = np.empty([0])
VidPerSubject = get_subfolders_num(inputDir, IgnoredSamples_index)
listOfIgnoredSamples = []
timesteps_TIM = 10
data_dim = r * w
pad_sequence = 10
#########################################################
############## Flags ####################
resizedFlag = 1
train_spatial_flag = 0
train_temporal_flag = 0
svm_flag = 1
finetuning_flag = 0
tensorboard_flag = 0
#########################################
############## Reading Images and Labels ################
SubperdB = Read_SMIC_Images(inputDir, listOfIgnoredSamples, dB, resizedFlag, table, workplace, spatial_size)
labelperSub = label_matching(workplace, dB, subjects, VidPerSubject)
######################################################################################
########### Model #######################
sgd = optimizers.SGD(lr=0.0001, decay=1e-7, momentum=0.9, nesterov=True)
adam = optimizers.Adam(lr=0.00001)
if train_spatial_flag == 0 and train_temporal_flag == 1:
data_dim = spatial_size * spatial_size
else:
data_dim = 4096
temporal_model = Sequential()
temporal_model.add(LSTM(2622, return_sequences=True, input_shape=(10, data_dim)))
temporal_model.add(LSTM(1000, return_sequences=False))
temporal_model.add(Dense(128, activation='relu'))
temporal_model.add(Dense(5, activation='sigmoid'))
temporal_model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=[metrics.categorical_accuracy])
#########################################
################# Pretrained Model ###################
vgg_model = VGG_16('VGG_Face_Deep_16.h5')
# keras_vgg = keras_vgg16(weights='imagenet')
# vgg_model = VGG_16('imagenet')
vgg_model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=[metrics.sparse_categorical_accuracy])
plot_model(vgg_model, to_file='model.png', show_shapes=True)
svm_classifier = SVC(kernel='linear', C=1)
######################################################