forked from iliiliiliili/KittiViewer-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.py
316 lines (284 loc) · 11.3 KB
/
backend.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import fire
import os
import numpy as np
import base64
import json
import time
from flask import Flask, jsonify, request
from flask_cors import CORS
import pickle
import sys
from functools import partial
from pathlib import Path
import second.core.box_np_ops as box_np_ops
import second.core.preprocess as prep
from second.core.box_coders import GroundBox3dCoder
from second.core.point_cloud.point_cloud_ops import points_to_voxel
from second.core.region_similarity import (
DistanceSimilarity, NearestIouSimilarity, RotateIouSimilarity)
from second.core.sample_ops import DataBaseSamplerV2
from second.core.target_assigner import TargetAssigner
from second.data import kitti_common as kitti
from second.protos import pipeline_pb2
from second.utils.eval import get_coco_eval_result, get_official_eval_result
from second.pytorch.inference import TorchInferenceContext
from second.utils.progress_bar import list_bar
app = Flask("second")
CORS(app)
class SecondBackend:
def __init__(self):
self.root_path = None
self.info_path = None
self.kitti_infos = None
self.image_idxes = None
self.dt_annos = None
self.inference_ctx = None
BACKEND = SecondBackend()
def error_response(msg):
response = {}
response["status"] = "error"
response["message"] = "[ERROR]" + msg
print("[ERROR]" + msg)
return response
@app.route('/api/readinfo', methods=['POST'])
def readinfo():
global BACKEND
instance = request.json
root_path = Path(instance["root_path"])
response = {"status": "normal"}
if not (root_path / "training").exists():
response["status"] = "error"
response["message"] = "ERROR: your root path is incorrect."
print("ERROR: your root path is incorrect.")
return response
BACKEND.root_path = root_path
info_path = Path(instance["info_path"])
if not info_path.exists():
response["status"] = "error"
response["message"] = "ERROR: info file not exist."
print("ERROR: your root path is incorrect.")
return response
BACKEND.info_path = info_path
with open(info_path, 'rb') as f:
kitti_infos = pickle.load(f)
BACKEND.kitti_infos = kitti_infos
BACKEND.image_idxes = [info["image_idx"] for info in kitti_infos]
response["image_indexes"] = BACKEND.image_idxes
response = jsonify(results=[response])
response.headers['Access-Control-Allow-Headers'] = '*'
return response
@app.route('/api/read_detection', methods=['POST'])
def read_detection():
global BACKEND
instance = request.json
det_path = Path(instance["det_path"])
response = {"status": "normal"}
if BACKEND.root_path is None:
return error_response("root path is not set")
if BACKEND.kitti_infos is None:
return error_response("kitti info is not loaded")
if Path(det_path).is_file():
with open(det_path, "rb") as f:
dt_annos = pickle.load(f)
else:
dt_annos = kitti.get_label_annos(det_path)
BACKEND.dt_annos = dt_annos
response = jsonify(results=[response])
response.headers['Access-Control-Allow-Headers'] = '*'
return response
@app.route('/api/get_pointcloud', methods=['POST'])
def get_pointcloud():
global BACKEND
instance = request.json
response = {"status": "normal"}
if BACKEND.root_path is None:
return error_response("root path is not set")
if BACKEND.kitti_infos is None:
return error_response("kitti info is not loaded")
image_idx = instance["image_idx"]
idx = BACKEND.image_idxes.index(image_idx)
kitti_info = BACKEND.kitti_infos[idx]
rect = kitti_info['calib/R0_rect']
P2 = kitti_info['calib/P2']
Trv2c = kitti_info['calib/Tr_velo_to_cam']
img_shape = kitti_info["img_shape"] # hw
wh = np.array(img_shape[::-1])
whwh = np.tile(wh, 2)
if 'annos' in kitti_info:
annos = kitti_info['annos']
labels = annos['name']
num_obj = len([n for n in annos['name'] if n != 'DontCare'])
dims = annos['dimensions'][:num_obj]
loc = annos['location'][:num_obj]
rots = annos['rotation_y'][:num_obj]
bbox = annos['bbox'][:num_obj] / whwh
gt_boxes_camera = np.concatenate(
[loc, dims, rots[..., np.newaxis]], axis=1)
gt_boxes = box_np_ops.box_camera_to_lidar(
gt_boxes_camera, rect, Trv2c)
box_np_ops.change_box3d_center_(gt_boxes, src=[0.5, 0.5, 0], dst=[0.5, 0.5, 0.5])
locs = gt_boxes[:, :3]
dims = gt_boxes[:, 3:6]
rots = np.concatenate([np.zeros([num_obj, 2], dtype=np.float32), -gt_boxes[:, 6:7]], axis=1)
frontend_annos = {}
response["locs"] = locs.tolist()
response["dims"] = dims.tolist()
response["rots"] = rots.tolist()
response["bbox"] = bbox.tolist()
response["labels"] = labels[:num_obj].tolist()
v_path = str(Path(BACKEND.root_path) / kitti_info['velodyne_path'])
with open(v_path, 'rb') as f:
pc_str = base64.encodestring(f.read())
response["pointcloud"] = pc_str.decode("utf-8")
if "with_det" in instance and instance["with_det"]:
if BACKEND.dt_annos is None:
return error_response("det anno is not loaded")
dt_annos = BACKEND.dt_annos[idx]
dims = dt_annos['dimensions']
num_obj = dims.shape[0]
loc = dt_annos['location']
rots = dt_annos['rotation_y']
bbox = dt_annos['bbox'] / whwh
labels = dt_annos['name']
dt_boxes_camera = np.concatenate(
[loc, dims, rots[..., np.newaxis]], axis=1)
dt_boxes = box_np_ops.box_camera_to_lidar(
dt_boxes_camera, rect, Trv2c)
box_np_ops.change_box3d_center_(dt_boxes, src=[0.5, 0.5, 0], dst=[0.5, 0.5, 0.5])
locs = dt_boxes[:, :3]
dims = dt_boxes[:, 3:6]
rots = np.concatenate([np.zeros([num_obj, 2], dtype=np.float32), -dt_boxes[:, 6:7]], axis=1)
response["dt_locs"] = locs.tolist()
response["dt_dims"] = dims.tolist()
response["dt_rots"] = rots.tolist()
response["dt_labels"] = labels.tolist()
response["dt_bbox"] = bbox.tolist()
response["dt_scores"] = dt_annos["score"].tolist()
# if "score" in annos:
# response["score"] = score.tolist()
response = jsonify(results=[response])
response.headers['Access-Control-Allow-Headers'] = '*'
print("send response!")
return response
@app.route('/api/get_image', methods=['POST'])
def get_image():
global BACKEND
instance = request.json
response = {"status": "normal"}
if BACKEND.root_path is None:
return error_response("root path is not set")
if BACKEND.kitti_infos is None:
return error_response("kitti info is not loaded")
image_idx = instance["image_idx"]
idx = BACKEND.image_idxes.index(image_idx)
kitti_info = BACKEND.kitti_infos[idx]
rect = kitti_info['calib/R0_rect']
P2 = kitti_info['calib/P2']
Trv2c = kitti_info['calib/Tr_velo_to_cam']
if 'img_path' in kitti_info:
img_path = kitti_info['img_path']
if img_path != "":
image_path = BACKEND.root_path / img_path
print(image_path)
with open(str(image_path), 'rb') as f:
image_str = f.read()
response["image_b64"] = base64.b64encode(image_str).decode("utf-8")
response["image_b64"] = 'data:image/{};base64,'.format(image_path.suffix[1:]) + response["image_b64"]
'''#
response["rect"] = rect.tolist()
response["P2"] = P2.tolist()
response["Trv2c"] = Trv2c.tolist()
response["L2CMat"] = ((rect @ Trv2c).T).tolist()
response["C2LMat"] = np.linalg.inv((rect @ Trv2c).T).tolist()
'''
print("send an image with size {}!".format(len(response["image_b64"])))
response = jsonify(results=[response])
response.headers['Access-Control-Allow-Headers'] = '*'
return response
@app.route('/api/build_network', methods=['POST'])
def build_network():
global BACKEND
instance = request.json
cfg_path = Path(instance["config_path"])
ckpt_path = Path(instance["checkpoint_path"])
response = {"status": "normal"}
if BACKEND.root_path is None:
return error_response("root path is not set")
if BACKEND.kitti_infos is None:
return error_response("kitti info is not loaded")
if not cfg_path.exists():
return error_response("config file not exist.")
if not ckpt_path.exists():
return error_response("ckpt file not exist.")
BACKEND.inference_ctx = TorchInferenceContext()
BACKEND.inference_ctx.build(str(cfg_path))
BACKEND.inference_ctx.restore(str(ckpt_path))
response = jsonify(results=[response])
response.headers['Access-Control-Allow-Headers'] = '*'
print("build_network successful!")
return response
@app.route('/api/inference_by_idx', methods=['POST'])
def inference_by_idx():
global BACKEND
instance = request.json
response = {"status": "normal"}
if BACKEND.root_path is None:
return error_response("root path is not set")
if BACKEND.kitti_infos is None:
return error_response("kitti info is not loaded")
if BACKEND.inference_ctx is None:
return error_response("inference_ctx is not loaded")
image_idx = instance["image_idx"]
idx = BACKEND.image_idxes.index(image_idx)
kitti_info = BACKEND.kitti_infos[idx]
v_path = str(Path(BACKEND.root_path) / kitti_info['velodyne_path'])
num_features = 4
points = np.fromfile(
str(v_path), dtype=np.float32,
count=-1).reshape([-1, num_features])
rect = kitti_info['calib/R0_rect']
P2 = kitti_info['calib/P2']
Trv2c = kitti_info['calib/Tr_velo_to_cam']
if 'img_shape' in kitti_info:
image_shape = kitti_info['img_shape']
points = box_np_ops.remove_outside_points(
points, rect, Trv2c, P2, image_shape)
print(points.shape[0])
img_shape = kitti_info["img_shape"] # hw
wh = np.array(img_shape[::-1])
whwh = np.tile(wh, 2)
t = time.time()
inputs = BACKEND.inference_ctx.get_inference_input_dict(
kitti_info, points)
print("input preparation time:", time.time() - t)
t = time.time()
with BACKEND.inference_ctx.ctx():
dt_annos = BACKEND.inference_ctx.inference(inputs)[0]
print("detection time:", time.time() - t)
dims = dt_annos['dimensions']
num_obj = dims.shape[0]
loc = dt_annos['location']
rots = dt_annos['rotation_y']
labels = dt_annos['name']
bbox = dt_annos['bbox'] / whwh
dt_boxes_camera = np.concatenate(
[loc, dims, rots[..., np.newaxis]], axis=1)
dt_boxes = box_np_ops.box_camera_to_lidar(
dt_boxes_camera, rect, Trv2c)
box_np_ops.change_box3d_center_(dt_boxes, src=[0.5, 0.5, 0], dst=[0.5, 0.5, 0.5])
locs = dt_boxes[:, :3]
dims = dt_boxes[:, 3:6]
rots = np.concatenate([np.zeros([num_obj, 2], dtype=np.float32), -dt_boxes[:, 6:7]], axis=1)
response["dt_locs"] = locs.tolist()
response["dt_dims"] = dims.tolist()
response["dt_rots"] = rots.tolist()
response["dt_labels"] = labels.tolist()
response["dt_scores"] = dt_annos["score"].tolist()
response["dt_bbox"] = bbox.tolist()
response = jsonify(results=[response])
response.headers['Access-Control-Allow-Headers'] = '*'
return response
def main(port=16666):
app.run(host='0.0.0.0', threaded=True, port=port)
if __name__ == '__main__':
fire.Fire()