-
Notifications
You must be signed in to change notification settings - Fork 278
/
predict_kitti.py
executable file
·200 lines (166 loc) · 7.22 KB
/
predict_kitti.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
from __future__ import division
import os
import cv2
import numpy as np
import pickle
import time
from keras_frcnn import config
from keras import backend as K
from keras.layers import Input
from keras.models import Model
from keras_frcnn import roi_helpers
import argparse
import os
import keras_frcnn.resnet as nn
from keras_frcnn.visualize import draw_boxes_and_label_on_image_cv2
def format_img_size(img, cfg):
""" formats the image size based on config """
img_min_side = float(cfg.im_size)
(height, width, _) = img.shape
if width <= height:
ratio = img_min_side / width
new_height = int(ratio * height)
new_width = int(img_min_side)
else:
ratio = img_min_side / height
new_width = int(ratio * width)
new_height = int(img_min_side)
img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
return img, ratio
def format_img_channels(img, cfg):
""" formats the image channels based on config """
img = img[:, :, (2, 1, 0)]
img = img.astype(np.float32)
img[:, :, 0] -= cfg.img_channel_mean[0]
img[:, :, 1] -= cfg.img_channel_mean[1]
img[:, :, 2] -= cfg.img_channel_mean[2]
img /= cfg.img_scaling_factor
img = np.transpose(img, (2, 0, 1))
img = np.expand_dims(img, axis=0)
return img
def format_img(img, C):
""" formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio
# Method to transform the coordinates of the bounding box to its original size
def get_real_coordinates(ratio, x1, y1, x2, y2):
real_x1 = int(round(x1 // ratio))
real_y1 = int(round(y1 // ratio))
real_x2 = int(round(x2 // ratio))
real_y2 = int(round(y2 // ratio))
return real_x1, real_y1, real_x2, real_y2
def predict_single_image(img_path, model_rpn, model_classifier_only, cfg, class_mapping):
st = time.time()
img = cv2.imread(img_path)
if img is None:
print('reading image failed.')
exit(0)
X, ratio = format_img(img, cfg)
if K.image_dim_ordering() == 'tf':
X = np.transpose(X, (0, 2, 3, 1))
# get the feature maps and output from the RPN
[Y1, Y2, F] = model_rpn.predict(X)
# this is result contains all boxes, which is [x1, y1, x2, y2]
result = roi_helpers.rpn_to_roi(Y1, Y2, cfg, K.image_dim_ordering(), overlap_thresh=0.7)
# convert from (x1,y1,x2,y2) to (x,y,w,h)
result[:, 2] -= result[:, 0]
result[:, 3] -= result[:, 1]
bbox_threshold = 0.8
# apply the spatial pyramid pooling to the proposed regions
boxes = dict()
for jk in range(result.shape[0] // cfg.num_rois + 1):
rois = np.expand_dims(result[cfg.num_rois * jk:cfg.num_rois * (jk + 1), :], axis=0)
if rois.shape[1] == 0:
break
if jk == result.shape[0] // cfg.num_rois:
# pad R
curr_shape = rois.shape
target_shape = (curr_shape[0], cfg.num_rois, curr_shape[2])
rois_padded = np.zeros(target_shape).astype(rois.dtype)
rois_padded[:, :curr_shape[1], :] = rois
rois_padded[0, curr_shape[1]:, :] = rois[0, 0, :]
rois = rois_padded
[p_cls, p_regr] = model_classifier_only.predict([F, rois])
for ii in range(p_cls.shape[1]):
if np.max(p_cls[0, ii, :]) < bbox_threshold or np.argmax(p_cls[0, ii, :]) == (p_cls.shape[2] - 1):
continue
cls_num = np.argmax(p_cls[0, ii, :])
if cls_num not in boxes.keys():
boxes[cls_num] = []
(x, y, w, h) = rois[0, ii, :]
try:
(tx, ty, tw, th) = p_regr[0, ii, 4 * cls_num:4 * (cls_num + 1)]
tx /= cfg.classifier_regr_std[0]
ty /= cfg.classifier_regr_std[1]
tw /= cfg.classifier_regr_std[2]
th /= cfg.classifier_regr_std[3]
x, y, w, h = roi_helpers.apply_regr(x, y, w, h, tx, ty, tw, th)
except Exception as e:
print(e)
pass
boxes[cls_num].append(
[cfg.rpn_stride * x, cfg.rpn_stride * y, cfg.rpn_stride * (x + w), cfg.rpn_stride * (y + h),
np.max(p_cls[0, ii, :])])
# add some nms to reduce many boxes
for cls_num, box in boxes.items():
boxes_nms = roi_helpers.non_max_suppression_fast(box, overlap_thresh=0.5)
boxes[cls_num] = boxes_nms
print(class_mapping[cls_num] + ":")
for b in boxes_nms:
b[0], b[1], b[2], b[3] = get_real_coordinates(ratio, b[0], b[1], b[2], b[3])
print('{} prob: {}'.format(b[0: 4], b[-1]))
img = draw_boxes_and_label_on_image_cv2(img, class_mapping, boxes)
print('Elapsed time = {}'.format(time.time() - st))
cv2.imshow('image', img)
result_path = './results_images/{}.png'.format(os.path.basename(img_path).split('.')[0])
print('result saved into ', result_path)
cv2.imwrite(result_path, img)
cv2.waitKey(0)
def predict(args_):
path = args_.path
with open('config.pickle', 'rb') as f_in:
cfg = pickle.load(f_in)
cfg.use_horizontal_flips = False
cfg.use_vertical_flips = False
cfg.rot_90 = False
class_mapping = cfg.class_mapping
if 'bg' not in class_mapping:
class_mapping['bg'] = len(class_mapping)
class_mapping = {v: k for k, v in class_mapping.items()}
input_shape_img = (None, None, 3)
input_shape_features = (None, None, 1024)
img_input = Input(shape=input_shape_img)
roi_input = Input(shape=(cfg.num_rois, 4))
feature_map_input = Input(shape=input_shape_features)
shared_layers = nn.nn_base(img_input, trainable=True)
# define the RPN, built on the base layers
num_anchors = len(cfg.anchor_box_scales) * len(cfg.anchor_box_ratios)
rpn_layers = nn.rpn(shared_layers, num_anchors)
classifier = nn.classifier(feature_map_input, roi_input, cfg.num_rois, nb_classes=len(class_mapping),
trainable=True)
model_rpn = Model(img_input, rpn_layers)
model_classifier_only = Model([feature_map_input, roi_input], classifier)
model_classifier = Model([feature_map_input, roi_input], classifier)
print('Loading weights from {}'.format(cfg.model_path))
model_rpn.load_weights(cfg.model_path, by_name=True)
model_classifier.load_weights(cfg.model_path, by_name=True)
model_rpn.compile(optimizer='sgd', loss='mse')
model_classifier.compile(optimizer='sgd', loss='mse')
if os.path.isdir(path):
for idx, img_name in enumerate(sorted(os.listdir(path))):
if not img_name.lower().endswith(('.bmp', '.jpeg', '.jpg', '.png', '.tif', '.tiff')):
continue
print(img_name)
predict_single_image(os.path.join(path, img_name), model_rpn,
model_classifier_only, cfg, class_mapping)
elif os.path.isfile(path):
print('predict image from {}'.format(path))
predict_single_image(path, model_rpn, model_classifier_only, cfg, class_mapping)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--path', '-p', default='images/000010.png', help='image path')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
predict(args)