MCPcopy Create free account
hub / github.com/AllentDan/LibtorchTutorials / Predict

Method Predict

lesson7-Detection/src/Detector.cpp:274–317  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

272}
273
274void Detector::Predict(cv::Mat image, bool show, float conf_thresh, float nms_thresh) {
275 int origin_width = image.cols;
276 int origin_height = image.rows;
277 cv::resize(image, image, { width,height });
278 auto img_tensor = torch::from_blob(image.data, { image.rows, image.cols, 3 }, torch::kByte);
279 img_tensor = img_tensor.permute({ 2, 0, 1 }).unsqueeze(0).to(torch::kFloat) / 255.0;
280
281 float anchor[12] = { 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 };
282 auto anchors_ = torch::from_blob(anchor, { 6,2 }, torch::TensorOptions(torch::kFloat32));
283 int image_size[2] = { width,height };
284 img_tensor = img_tensor.to(device);
285
286 auto outputs = detector->forward(img_tensor);
287 std::vector<torch::Tensor> output_list = {};
288 auto tensor_input = outputs[1];
289 auto output_decoded = DecodeBox(tensor_input, anchors_.narrow(0, 0, 3), name_list.size(), image_size);
290 output_list.push_back(output_decoded);
291
292 tensor_input = outputs[0];
293 output_decoded = DecodeBox(tensor_input, anchors_.narrow(0, 3, 3), name_list.size(), image_size);
294 output_list.push_back(output_decoded);
295
296 //std::cout << tensor_input << anchors_.narrow(0, 3, 3);
297
298 auto output = torch::cat(output_list, 1);
299 auto detection = non_maximum_suppression(output, name_list.size(), conf_thresh, nms_thresh);
300
301 float w_scale = float(origin_width) / width;
302 float h_scale = float(origin_height) / height;
303 for (int i = 0; i < detection.size(); i++) {
304 for (int j = 0; j < detection[i].size(0) / 7; j++)
305 {
306 detection[i].select(0, 7 * j + 0) *= w_scale;
307 detection[i].select(0, 7 * j + 1) *= h_scale;
308 detection[i].select(0, 7 * j + 2) *= w_scale;
309 detection[i].select(0, 7 * j + 3) *= h_scale;
310 }
311 }
312
313 cv::resize(image, image, { origin_width,origin_height });
314 if(show)
315 show_bbox(image, detection[0], name_list);
316 return;
317}

Callers 1

mainFunction · 0.45

Calls 6

DecodeBoxFunction · 0.85
non_maximum_suppressionFunction · 0.85
show_bboxFunction · 0.85
push_backMethod · 0.80
forwardMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected