-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetect_oneImage.py~
executable file
·248 lines (197 loc) · 9.07 KB
/
detect_oneImage.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
# Copyright (c) 2016 Matthew Earl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
Routines to detect number plates.
Use `detect` to detect all bounding boxes, and use `post_process` on the output
of `detect` to filter using non-maximum suppression.
python3 ../detect_oneImage.py orig1-plateOnly-glb-172.jpg /home/mka/PycharmProjects/deep-anpr-x64-y32/weights.npz
python3 ../detect_oneImage.py orig1-plateOnly-glb-172.jpg /home/mka/PycharmProjects/deep-anpr-x64-y32-finplate/weights1.npz
"""
import collections
import itertools
import math
import sys
import cv2
import numpy as np
import tensorflow as tf
import Image2Characters.model
from scipy.optimize import minimize, fmin_l_bfgs_b, fmin_powell, \
basinhopping, differential_evolution, brute
from matplotlib import pyplot as plt
__all__ = (
'DIGITS',
'LETTERS',
'CHARS',
'sigmoid',
'softmax',
)
import numpy
DIGITS = "0123456789"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CHARS = LETTERS + DIGITS + '-'
def softmax(a):
exps = numpy.exp(a.astype(numpy.float64))
return exps / numpy.sum(exps, axis=-1)[:, numpy.newaxis]
def sigmoid(a):
return 1. / (1. + numpy.exp(-a))
class RandomDisplacementBounds(object):
"""random displacement with bounds"""
def __init__(self, xmin, xmax, stepsize=0.05):
self.xmin = xmin
self.xmax = xmax
self.stepsize = stepsize
def __call__(self, x):
"""take a random step but ensure the new position is within the bounds"""
while True:
# this could be done in a much more clever way, but it will work for example purposes
xnew = x + np.random.uniform(-self.stepsize, self.stepsize, np.shape(x))
if np.all(xnew < self.xmax) and np.all(xnew > self.xmin):
break
return xnew
class Detect():
""" maximaze the probability of a plate as seen by the trained neural network
we search the best window in the image
(upperleft x and y, and width and height in the image)
give the letters of the plate for this subimage """
def __init__(self, image=None, param_vals=None):
self.image = image # image containing the number plate
self.param_vals = param_vals # neural network optimal values from train.py
self.uly = 10 # upper left y of the portion
self.ulx = 10 # upper left x of the portion
self.lry = image.shape[0]-10 # width of the portion
self.lrx = image.shape[1]-10 # heigth of the portion
self.prob = None # final probability
self.best_letters = None # final characters of the plage
self.scale=1e-8 # trick to get scipy minimize work for integer function
self.best = 1.0
self.best_rectangle = None
def setNpImage(self,image):
self.image=image
def get_best(self):
return self.best, self.best_letters
def get_best_rectangle(self):
return self.best_rectangle
def make_scaled_im(self, clone):
return cv2.resize(clone, (model.WINDOW_SHAPE[1], model.WINDOW_SHAPE[0]))
def maximise_prob(self):
""" by scipy cg, find the portion of the image that gives max probability of a plate"""
x0 = np.asarray([0.1,0.1,0.9,0.9])
#direc=np.asarray([100,100,-100,-100])
bnds = ((0.0, 1.0), (0.0, 1.0),
(0.0, 1.0), (0.0, 1.0))
rranges = (slice(0, self.image.shape[0], 10),
slice(0, self.image.shape[1], 10),
slice(0, self.image.shape[0], 10),
slice(0, self.image.shape[1], 10))
print(bnds)
print("x0",x0)
res = brute(self.detect, rranges)
# res = differential_evolution(func=self.detect, bounds=bnds, strategy='best1exp', popsize=5, mutation=1.99)
#res = minimize(self.detect, x0, method='SLSQP', bounds=bnds, options = {'eps': 0.5})
#BASIN define the new step taking routine and pass it to basinhopping
#BASIN take_step = RandomDisplacementBounds(0, 1)
#BASIN minimizer_kwargs = dict(method="SLSQP", bounds=bnds, options={'maxiter':1})
#BASIN res = basinhopping(self.detect, x0, T=0.001, minimizer_kwargs=minimizer_kwargs,take_step=take_step)
#res = minimize(self.detect, x0, method='SLSQP')
#xx,yy,zz = fmin_powell(self.detect, x0, direc=direc)
#xval,fval,other = fmin_l_bfgs_b(func=self.detect, x0=x0, approx_grad=True, bounds=bnds)
#xval,fval,other = fmin_l_bfgs_b(func=g, x0=x0, approx_grad=True)
print("result1", res)
def letter_probs_to_code(self, letter_probs):
return "".join(CHARS[i] for i in np.argmax(letter_probs, axis=1))
def g2(self, x):
res = x[0] + x[1] - x[2] - x[3]
return res
def detect(self, x):
"""
Detect number plates in an image.
:param x
area in image xtopleft, ytopleft, width, height
"""
xarea = x.copy()
#xarea[0] = x[0]*self.image.shape[0]
#xarea[2] = x[2]*self.image.shape[0]
#xarea[1] = x[1]*self.image.shape[1]
#xarea[3] = x[3]*self.image.shape[1]
#xarea = xarea.astype(int)
#small_image = self.image.copy()[xarea[1]:(xarea[1]+xarea[3]),
# xarea[0]:(xarea[0] + xarea[2])]
# Convert the image to various scales.
#scaled_im = self.make_scaled_im(small_image.copy())
scaled_im = self.make_scaled_im(self.image.copy())
# Load the model which detects number plates over a sliding window.
xx, yy, params = model.get_detect_model()
plt.imshow(scaled_im)
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
present_prob=0.0
# Execute the model at each scale.
with tf.Session(config=tf.ConfigProto()) as sess:
y_vals = []
feed_dict = {xx: np.stack([scaled_im])}
feed_dict.update(dict(zip(params, self.param_vals)))
y_vals.append(sess.run(yy, feed_dict=feed_dict))
# Interpret the results in terms of bounding boxes in the input image.
# Do this by identifying windows (at all scales)
# where the model predicts a
# number plate has a greater than 50% probability of appearing.
#
# To obtain pixel coordinates,
# the window coordinates are scaled according
# to the stride size, and pixel coordinates.
i=0; y_val = y_vals[0]
for window_coords in np.argwhere(y_val[0, :, :, 0] > -math.log(1./0.001 - 1)):
letter_probs = (y_val[0,
window_coords[0],
window_coords[1], 1:].reshape(
7, len(CHARS)))
letter_probs = softmax(letter_probs)
img_scale = float(1)
present_prob = sigmoid(
y_val[0, window_coords[0], window_coords[1], 0])
print(present_prob, self.letter_probs_to_code(letter_probs))
if present_prob > 0.0:
letters = self.letter_probs_to_code(letter_probs)
else:
letters = None
result = 1.0-present_prob
if result < self.best:
self.best = 1.0-present_prob
self.best_letters = letters
self.best_rectangle = xarea
print("returning",result)
return result
if __name__ == "__main__":
im_gray = cv2.imread(sys.argv[1])[:, :, 0].astype(numpy.float32) / 255.
#im = cv2.imread(sys.argv[1])
#try:
# im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
#except:
# im_gray = im
f = np.load(sys.argv[2])
param_vals = [f[n] for n in sorted(f.files, key=lambda s: int(s[4:]))]
print(im_gray.shape)
#plt.imshow(im_gray)
#plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
#plt.show()
app = Detect(image=im_gray, param_vals = param_vals)
#app.maximise_prob()
#detect(im_gray[27:120,140:480], param_vals)
app.detect(im_gray)