-
Notifications
You must be signed in to change notification settings - Fork 0
/
nn.py
178 lines (152 loc) · 5.09 KB
/
nn.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
import cv2
import numpy as np
import tensorflow as tf
import os
np.set_printoptions(threshold=20)
def isvalid(img,i,j):
if(i<0 or j<0 or i>=img.shape[0] or j>=img.shape[1]):
return 0
return 1
def HOG(img):
X=np.array(img)
X=np.reshape(X,64*64*3)
return X
# winSize=(64,64)
# blockSize=(16,16)
# blockStride=(8,8)
# cellSize=(8,8)
# nbins=9
# derivAperture = 1
# winSigma = 4.
# histogramNormType = 0
# L2HysThreshold = 2.0000000000000001e-01
# gammaCorrection = 0
# nlevels = 64
# hog=cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,histogramNormType,L2HysThreshold,gammaCorrection,nlevels)
# return hog.compute(img)
def images_and_hog(folder):
X=[]
X_test=[]
count=0
count_test=0
for file in os.listdir(folder):
img=cv2.imread(os.path.join(folder,file))
if img is not None:
img=cv2.resize(img,(64,64))
feat=HOG(img)
count+=1
if(count%10==0):
X_test.append(feat)
count_test+=1
else:
X.append(feat)
X=np.array(X)
X=np.reshape(X,(count-count_test,64*64*3))
X_test=np.reshape(X_test,(count_test,64*64*3))
return X,X_test
#**************Training***********
X=np.array([])
X_test=np.array([])
for i in range (0,42):
folder='./dataset_old/0'+str(i) if i<10 else './dataset_old/'+str(i)
x,x_test=images_and_hog(folder)
X=np.append(X,x)
X_test=np.append(X_test,x_test)
X=np.reshape(X,(-1,64*64*3))
X_test=np.reshape(X_test,(-1,64*64*3))
print "Shape=",X.shape,X_test.shape
Y=np.array([1 for i in range(0,X.shape[0])])
num_positive_example=X.shape[0]
num_positive_test=X_test.shape[0]
Y_test=np.array([1 for i in range(0,X_test.shape[0])])
print "Positive exm ",num_positive_example
folder='./neg_exm/'#'./dataset/non_signs/'
x,x_test=images_and_hog(folder)
x=x[np.random.choice(x.shape[0],size=1100,replace=False),:]
X=np.append(X,x)
X_test=np.append(X_test,x_test)
X=np.reshape(X,(-1,64*64*3))
X_test=np.reshape(X_test,(-1,64*64*3))
print X.shape[0]
Y=np.append(Y,[0 for i in range(0,X.shape[0]-num_positive_example)])
Y=np.reshape(Y,(-1,1))
Y_test=np.append(Y_test,[0 for i in range(0,X_test.shape[0]-num_positive_test)])
Y_test=np.reshape(Y_test,(-1,1))
# X=np.append(X,X_test)
# Y=np.append(Y,Y_test)
Y=np.reshape(Y,(-1,1))
X=np.reshape(X,(-1,64*64*3))
X=np.array(X,dtype=np.float32)
Y=np.array(Y,dtype=np.float32)
print "shape =",X.shape,Y.shape
X_=tf.placeholder(tf.float32,[None,64*64*3])
Y_=tf.placeholder(tf.float32,[None,1])
W1=tf.Variable(tf.random_normal([64*64*3,2000],stddev=0.1))
b1=tf.Variable(tf.constant(0.1,shape=[2000]))
W2=tf.Variable(tf.random_normal([2000,2000],stddev=0.1))
b2=tf.Variable(tf.constant(0.1,shape=[2000]))
W3=tf.Variable(tf.random_normal([2000,1],stddev=0.1))
b3=tf.Variable(tf.constant(0.1))
layer_1=tf.add(tf.matmul(X_,W1),b1)
layer_1=tf.nn.relu(layer_1)
layer_2=tf.add(tf.matmul(layer_1,W2),b2)
layer_2=tf.nn.relu(layer_2)
out=tf.add(tf.matmul(layer_2,W3),b3)
out=tf.nn.sigmoid(out)
# cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y_,logits=out))
cost=tf.reduce_mean(-1*Y_*tf.log(tf.clip_by_value(out,1e-10,0.0001))-1*(1-Y_)*tf.log(tf.clip_by_value(1-out,1e-10,0.0001)))
train_step=tf.train.GradientDescentOptimizer(1e-4).minimize(cost)
p=tf.constant(0.5,shape=[1])
print Y_
print out
print p
correct_prediction=tf.equal(tf.where(tf.less(p,out),tf.constant(1.0,shape=[989,1]),tf.constant(0.0,shape=[989,1])),Y_)
Accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))*100
tf.summary.scalar("cost",cost)
# tf.scalar_summary("accuracy",Accuracy)
summary_op=tf.summary.merge_all()
sess=tf.InteractiveSession()
tf.global_variables_initializer().run()
# tf.reset_default_graph()
writer=tf.summary.FileWriter('./Graph_pix',sess.graph)
saver=tf.train.Saver([W1,b1,W2,b2,W3,b3])
for i in range(0,500):
sess.run(train_step,feed_dict={X_:X,Y_:Y})
summary=sess.run(summary_op,feed_dict={X_:X,Y_:Y})
writer.add_summary(summary,i)
if(i%20==0):
print i
if(i%50==0):
print(out.eval(feed_dict={X_:X_test,Y_:Y_test}))
print("Accuracy : ",Accuracy.eval(feed_dict={X_:X_test,Y_:Y_test}))
saver.save(sess,'./tf_model_pix/restore.ckpt')
print("Successfully trained")
# print("Final Accuracy : ",Accuracy.eval(feed_dict={X_:X_test,Y_:Y_test}))
# print(out.eval(feed_dict={X_:X_test,Y_:Y_test}))
# saver=tf.train.Saver([W1,b1,W2,b2,W3,b3])
# saver.restore(sess,'./tf_model/restore.ckpt')
# print "Restored"
test=cv2.imread('./images/00023.ppm')#dataset/03/00011.ppm')
print 'testing'
d = 0
output=np.zeros((test.shape[0],test.shape[1],3),dtype=np.uint8)
for i in range(0,test.shape[0]):
for j in range(0,test.shape[1]):
output[i,j]=test[i,j]
for i in range(0,test.shape[0],10):
for j in range(0,test.shape[1],10):
if(isvalid(test,i+64,j+64)==0):
continue
if(i%100==0 and j%100==0):
print i,j
patch=test[[k for k in range(i,i+64)],:,:]
patch=patch[:,[k for k in range(j,j+64)],:]
if(out.eval(feed_dict={X_:np.reshape(HOG(patch),(-1,64*64*3))})>[0.75]):
P1=(j,i)
P4=(j+64,i+64)
cv2.rectangle(output,P1,P4,[0,0,255],thickness=1)
#cv2.imshow("box", out[i:i+64, j:j+64, :]); cv2.waitKey(0);
# cv2.imwrite("detected"+str(d)+".png", out[i:i+64, j:j+64, :])
d=d+1
cv2.imshow("out",output)
cv2.waitKey(0)