-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCNN
188 lines (153 loc) · 5.38 KB
/
CNN
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
import os
import sys
import numpy as np
import cv2
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Dropout, Flatten ,BatchNormalization
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
IMAGE_SIZE = 48
#按照指定影象大小調整尺寸
def resize_image(image, height = IMAGE_SIZE, width = IMAGE_SIZE):
top, bottom, left, right = (0, 0, 0, 0)
#獲取影象尺寸
h, w, _ = image.shape
#對於長寬不相等的圖片,找到最長的一邊
longest_edge = max(h, w)
#計算短邊需要增加多上畫素寬度使其與長邊等長
if h < longest_edge:
dh = longest_edge - h
top = dh // 2
bottom = dh - top
elif w < longest_edge:
dw = longest_edge - w
left = dw // 2
right = dw - left
else:
pass
#RGB顏色
BLACK = [0, 0, 0]
#給影象增加邊界,是圖片長、寬等長,cv2.BORDER_CONSTANT指定邊界顏色由value指定
constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value = BLACK)
#調整影象大小並返回
return cv2.resize(constant, (height, width))
#讀取訓練資料
fall = "C:\Harden_project\project4_fall\跌倒照片"
stand = ""
images = []
labels = []
dir_counts = 0
for i in os.listdir(face1):
img1 = cv2.imread(face1+"/"+i)
img1 = resize_image(img1, IMAGE_SIZE, IMAGE_SIZE)
images.append(img1)
labels.append(dir_counts)
#a = np.array(images,dtype=np.float32)
#print(a.shape)
for i in os.listdir(face):
img2 = cv2.imread(face+"/"+i)
img2 = resize_image(img2, IMAGE_SIZE, IMAGE_SIZE)
images.append(img2)
labels.append(dir_counts+1)
for i in os.listdir(face2):
img3 = cv2.imread(face2+"/"+i)
img3 = resize_image(img3, IMAGE_SIZE, IMAGE_SIZE)
images.append(img3)
labels.append(dir_counts+2)
for i in os.listdir(face3):
img4 = cv2.imread(face3+"/"+i)
img4 = resize_image(img4, IMAGE_SIZE, IMAGE_SIZE)
images.append(img4)
labels.append(dir_counts+3)
label = np.array(labels)
print(len(label))
print(label)
#labels = np.array([0 if label.endswith('face0') else 1 for label in labels])
#print(type(labels))
#########CNN############
#print(images)
X_train_img,X_test_img,y_train_label,y_test_label = train_test_split(images, label,test_size=0.3,random_state=2 )#
X_train = np.array(X_train_img, dtype=np.float32)
X_test = np.array(X_test_img, dtype=np.float32)
print(X_train.shape)
x_train_std = X_train/255
x_test_std = X_test/255
y_trainOneHot = np_utils.to_categorical(y_train_label)
y_testOneHot = np_utils.to_categorical(y_test_label)
print(x_test_std.shape)
print(y_test_label)
#x_train_std = x_train_std.reshape(x_train_std.shape[0],-1)
#x_test_std = x_test_std.reshape(x_test_std.shape[0],-1)
print(len(x_train_std))
#建立模組
#cnn modle
model = Sequential()
#捲積層conv2D
model.add(Conv2D(filters = 48, kernel_size=(5,5), padding='same',input_shape=(48,48,3),activation = 'relu'))
model.add(Dropout(0.5))
model.add(Conv2D(filters = 48, kernel_size=(5,5), padding='same',input_shape=(48,48,3),activation = 'relu'))
#化池層MaxPooling2D
model.add(MaxPooling2D(pool_size=(2,2)))
#conv2D *2
model.add(Conv2D(filters=192, kernel_size=(3,3),padding ='same',activation='relu'))
model.add(Dropout(0.5))
model.add(Conv2D(filters=384, kernel_size=(3,3),padding ='same',activation='relu'))
#Maxpooling2D *2
model.add(MaxPooling2D(pool_size=(2,2)))
#捲積層conv2D*3
model.add(Conv2D(filters= 384,kernel_size=(3,3),activation='relu',padding='same'))
model.add(Dropout(0.5))
model.add(Conv2D(filters= 768,kernel_size=(3,3),activation='relu',padding='same'))
#Maxpooling2D *3
model.add(MaxPooling2D(pool_size=(2,2)))
#平坦層Flatten壓平變成一維 64X8X8=4096
model.add(Flatten())
#Drop
model.add(Dropout(0.6))
#隱藏layer
model.add(Dense(3072,kernel_initializer='normal',activation='relu'))
#Drop
model.add(Dropout(0.5))
#model.add(Dropout(0.3))
#隱藏layer2
model.add(Dense(1536,kernel_initializer='normal',activation='relu'))
#Drop
model.add(Dropout(0.5))
#輸出layer
model.add(Dense(4,activation='softmax'))
#summary
print(model.summary())
with open('CNN3.h5', 'w') as fp:
pass
try:
model.load_weights("CNN3.h5")
print("載入模型成功")
except:
print("載入模型失敗")
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
model.fit(x=x_train_std,y=y_trainOneHot,validation_split=0.2,epochs=50,batch_size=100,verbose=1)
scores = model.evaluate(x_test_std,y_testOneHot,verbose=1)
model.save("CNN4.h5")
print("Save mode to disk")
prediction= model.predict_classes(x_test_std)
print("幹",scores[1])
import pandas as pd
def plot_image(image,labels,prediction,idx,num=10):
fig = plt.gcf()
fig.set_size_inches(12, 14)
if num>25:
num=25
for i in range(0, num):
ax = plt.subplot(5,5, 1+i)
ax.imshow(image[idx], cmap='binary')
title = "label=" +str(labels[idx])
if len(prediction)>0:
title+=",perdict="+str(prediction[idx])
ax.set_title(title,fontsize=10)
ax.set_xticks([]);ax.set_yticks([])
idx+=1
plt.show()
p =confusion_amtrix =pd.crosstab(np.array(y_test_label),prediction, rownames=['label'],colnames=['perdict'],margins = True)
print(p)
plot_image(x_test_std,y_test_label,prediction,idx=10)