-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdetect.py
183 lines (135 loc) · 5.59 KB
/
detect.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
__all__ = (
'detect',
'post_process',
)
import collections
import itertools
import math
import sys
import cv2
import numpy
import tensorflow as tf
import common
import model
def make_scaled_ims(im, min_shape):
ratio = 1. / 2 ** 0.5
shape = (im.shape[0] / ratio, im.shape[1] / ratio)
while True:
shape = (int(shape[0] * ratio), int(shape[1] * ratio))
if shape[0] < min_shape[0] or shape[1] < min_shape[1]:
break
yield cv2.resize(im, (shape[1], shape[0]))
def detect(im, param_vals):
"""
Detect number plates in an image.
:param im:
Image to detect number plates in.
:param param_vals:
Model parameters to use. These are the parameters output by the `train`
module.
:returns:
Iterable of `bbox_tl, bbox_br, letter_probs`, defining the bounding box
top-left and bottom-right corners respectively, and a 7,36 matrix
giving the probability distributions of each letter.
"""
# Convert the image to various scales.
scaled_ims = list(make_scaled_ims(im, model.WINDOW_SHAPE))
# Load the model which detects number plates over a sliding window.
x, y, params = model.get_detect_model()
# Execute the model at each scale.
with tf.Session(config=tf.ConfigProto()) as sess:
y_vals = []
for scaled_im in scaled_ims:
feed_dict = {x: numpy.stack([scaled_im])}
feed_dict.update(dict(zip(params, param_vals)))
y_vals.append(sess.run(y, 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.
for i, (scaled_im, y_val) in enumerate(zip(scaled_ims, y_vals)):
for window_coords in numpy.argwhere(y_val[0, :, :, 0] >
-math.log(1./0.99 - 1)):
letter_probs = (y_val[0,
window_coords[0],
window_coords[1], 1:].reshape(
7, len(common.CHARS)))
letter_probs = common.softmax(letter_probs)
img_scale = float(im.shape[0]) / scaled_im.shape[0]
bbox_tl = window_coords * (8, 4) * img_scale
bbox_size = numpy.array(model.WINDOW_SHAPE) * img_scale
present_prob = common.sigmoid(
y_val[0, window_coords[0], window_coords[1], 0])
yield bbox_tl, bbox_tl + bbox_size, present_prob, letter_probs
def _overlaps(match1, match2):
bbox_tl1, bbox_br1, _, _ = match1
bbox_tl2, bbox_br2, _, _ = match2
return (bbox_br1[0] > bbox_tl2[0] and
bbox_br2[0] > bbox_tl1[0] and
bbox_br1[1] > bbox_tl2[1] and
bbox_br2[1] > bbox_tl1[1])
def _group_overlapping_rectangles(matches):
matches = list(matches)
num_groups = 0
match_to_group = {}
for idx1 in range(len(matches)):
for idx2 in range(idx1):
if _overlaps(matches[idx1], matches[idx2]):
match_to_group[idx1] = match_to_group[idx2]
break
else:
match_to_group[idx1] = num_groups
num_groups += 1
groups = collections.defaultdict(list)
for idx, group in match_to_group.items():
groups[group].append(matches[idx])
return groups
def post_process(matches):
"""
Take an iterable of matches as returned by `detect` and merge duplicates.
Merging consists of two steps:
- Finding sets of overlapping rectangles.
- Finding the intersection of those sets, along with the code
corresponding with the rectangle with the highest presence parameter.
"""
groups = _group_overlapping_rectangles(matches)
for group_matches in groups.values():
mins = numpy.stack(numpy.array(m[0]) for m in group_matches)
maxs = numpy.stack(numpy.array(m[1]) for m in group_matches)
present_probs = numpy.array([m[2] for m in group_matches])
letter_probs = numpy.stack(m[3] for m in group_matches)
yield (numpy.max(mins, axis=0).flatten(),
numpy.min(maxs, axis=0).flatten(),
numpy.max(present_probs),
letter_probs[numpy.argmax(present_probs)])
def letter_probs_to_code(letter_probs):
return "".join(common.CHARS[i] for i in numpy.argmax(letter_probs, axis=1))
if __name__ == "__main__":
im = cv2.imread(sys.argv[1])
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) / 255.
f = numpy.load(sys.argv[2])
param_vals = [f[n] for n in sorted(f.files, key=lambda s: int(s[4:]))]
for pt1, pt2, present_prob, letter_probs in post_process(
detect(im_gray, param_vals)):
pt1 = tuple(reversed(map(int, pt1)))
pt2 = tuple(reversed(map(int, pt2)))
code = letter_probs_to_code(letter_probs)
color = (0.0, 255.0, 0.0)
cv2.rectangle(im, pt1, pt2, color)
cv2.putText(im,
code,
pt1,
cv2.FONT_HERSHEY_PLAIN,
1.5,
(0, 0, 0),
thickness=5)
cv2.putText(im,
code,
pt1,
cv2.FONT_HERSHEY_PLAIN,
1.5,
(255, 255, 255),
thickness=2)
cv2.imwrite(sys.argv[3], im)