1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-31 00:03:03 +04:00

Merge pull request #25710 from gursimarsingh:improved_object_detection_sample

Merged yolo_detector and object detection sample #25710

Relates to #25006

This pull request merges the yolo_detector.cpp sample with the object_detector.cpp sample. It also beautifies the bounding box display on the output images

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
This commit is contained in:
Gursimar Singh
2024-09-18 18:49:46 +05:30
committed by GitHub
parent 46b800f506
commit e823493af1
6 changed files with 684 additions and 790 deletions
+467 -247
View File
@@ -1,68 +1,114 @@
//![includes]
#include <fstream>
#include <sstream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#if defined(HAVE_THREADS)
#define USE_THREADS 1
#endif
#ifdef USE_THREADS
#include <mutex>
#include <thread>
#include <queue>
#endif
#include "iostream"
#include "common.hpp"
std::string param_keys =
"{ help h | | Print help message. }"
"{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }"
"{ zoo | models.yml | An optional path to file with preprocessing parameters }"
"{ device | 0 | camera device number. }"
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera. }"
"{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
"{ classes | | Optional path to a text file with names of classes to label detected objects. }"
"{ thr | .5 | Confidence threshold. }"
"{ nms | .4 | Non-maximum suppression threshold. }"
"{ async | 0 | Number of asynchronous forwards at the same time. "
"Choose 0 for synchronous mode }";
std::string backend_keys = cv::format(
"{ backend | 0 | Choose one of computation backends: "
"%d: automatically (by default), "
"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"%d: OpenCV implementation, "
"%d: VKCOM, "
"%d: CUDA }", cv::dnn::DNN_BACKEND_DEFAULT, cv::dnn::DNN_BACKEND_INFERENCE_ENGINE, cv::dnn::DNN_BACKEND_OPENCV, cv::dnn::DNN_BACKEND_VKCOM, cv::dnn::DNN_BACKEND_CUDA);
std::string target_keys = cv::format(
"{ target | 0 | Choose one of target computation devices: "
"%d: CPU target (by default), "
"%d: OpenCL, "
"%d: OpenCL fp16 (half-float precision), "
"%d: VPU, "
"%d: Vulkan, "
"%d: CUDA, "
"%d: CUDA fp16 (half-float preprocess) }", cv::dnn::DNN_TARGET_CPU, cv::dnn::DNN_TARGET_OPENCL, cv::dnn::DNN_TARGET_OPENCL_FP16, cv::dnn::DNN_TARGET_MYRIAD, cv::dnn::DNN_TARGET_VULKAN, cv::dnn::DNN_TARGET_CUDA, cv::dnn::DNN_TARGET_CUDA_FP16);
std::string keys = param_keys + backend_keys + target_keys;
//![includes]
using namespace cv;
using namespace dnn;
using namespace std;
float confThreshold, nmsThreshold;
std::vector<std::string> classes;
const string about =
"Firstly, download required models using `download_models.py` (if not already done). Set environment variable OPENCV_DOWNLOAD_CACHE_DIR to specify where models should be downloaded. Also, point OPENCV_SAMPLES_DATA_PATH to opencv/samples/data.\n"
"To run:\n"
"\t ./example_dnn_object_detection model_name --input=path/to/your/input/image/or/video (don't give --input flag if want to use device camera)\n"
"Sample command:\n"
"\t ./example_dnn_object_detection yolov8 --input=$OPENCV_SAMPLES_DATA_PATH/baboon.jpg\n"
inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
const Scalar& mean, bool swapRB);
"Model path can also be specified using --model argument. ";
void postprocess(Mat& frame, const std::vector<Mat>& out, Net& net, int backend);
const string param_keys =
"{ help h | | Print help message. }"
"{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }"
"{ zoo | ../dnn/models.yml | An optional path to file with preprocessing parameters }"
"{ device | 0 | camera device number. }"
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera. }"
"{ thr | .5 | Confidence threshold. }"
"{ nms | .4 | Non-maximum suppression threshold. }"
"{ async | 0 | Number of asynchronous forwards at the same time. "
"Choose 0 for synchronous mode }"
"{ padvalue | 114.0 | padding value. }"
"{ paddingmode | 2 | Choose one of padding modes: "
"0: resize to required input size without extra processing, "
"1: Image will be cropped after resize, "
"2: Resize image to the desired size while preserving the aspect ratio of original image }";
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);
const string backend_keys = format(
"{ backend | default | Choose one of computation backends: "
"default: automatically (by default), "
"openvino: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"opencv: OpenCV implementation, "
"vkcom: VKCOM, "
"cuda: CUDA, "
"webnn: WebNN }");
void callback(int pos, void* userdata);
const string target_keys = format(
"{ target | cpu | Choose one of target computation devices: "
"cpu: CPU target (by default), "
"opencl: OpenCL, "
"opencl_fp16: OpenCL fp16 (half-float precision), "
"vpu: VPU, "
"vulkan: Vulkan, "
"cuda: CUDA, "
"cuda_fp16: CUDA fp16 (half-float preprocess) }");
string keys = param_keys + backend_keys + target_keys;
float confThreshold, nmsThreshold, scale, paddingValue;
vector<string> labels;
Scalar meanv;
bool swapRB;
int inpWidth, inpHeight;
size_t asyncNumReq = 0;
ImagePaddingMode paddingMode;
string modelName, framework;
static void preprocess(const Mat& frame, Net& net, Size inpSize);
static void postprocess(Mat& frame, const vector<Mat>& outs, Net& net, int backend, vector<int>& classIds, vector<float>& confidences, vector<Rect>& boxes, const string yolo_name);
static void drawPred(vector<int>& classIds, vector<float>& confidences, vector<Rect>& boxes, Mat& frame, FontFace& sans, int stdSize, int stdWeight, int stdImgSize, int stdThickness);
static void callback(int pos, void* userdata);
static Scalar getColor(int classId);
static void yoloPostProcessing(
const vector<Mat>& outs,
vector<int>& keep_classIds,
vector<float>& keep_confidences,
vector<Rect2d>& keep_boxes,
float conf_threshold,
float iou_threshold,
const string& yolo_name);
static void printAliases(string& zooFile){
vector<string> aliases = findAliases(zooFile, "object_detection");
cout<<"Alias choices: [ ";
for (auto it: aliases){
cout<<"'"<<it<<"' ";
}
cout<<"]"<<endl;
}
static Scalar getTextColor(Scalar bgColor) {
double luminance = 0.299 * bgColor[2] + 0.587 * bgColor[1] + 0.114 * bgColor[0];
return luminance > 128 ? Scalar(0, 0, 0) : Scalar(255, 255, 255);
}
#ifdef USE_THREADS
template <typename T>
class QueueFPS : public std::queue<T>
{
@@ -112,233 +158,362 @@ private:
TickMeter tm;
std::mutex mutex;
};
#endif // USE_THREADS
int main(int argc, char** argv)
{
CommandLineParser parser(argc, argv, keys);
const std::string modelName = parser.get<String>("@alias");
const std::string zooFile = parser.get<String>("zoo");
string zooFile = parser.get<String>("zoo");
if (!parser.has("@alias") || parser.has("help"))
{
cout << about << endl;
parser.printMessage();
printAliases(zooFile);
return -1;
}
zooFile = findFile(zooFile);
modelName = parser.get<String>("@alias");
keys += genPreprocArguments(modelName, zooFile);
parser = CommandLineParser(argc, argv, keys);
parser.about("Use this script to run object detection deep learning networks using OpenCV.");
if (argc == 1 || parser.has("help"))
if (!parser.has("model"))
{
parser.printMessage();
return 0;
cout << "Path to model is not provided in command line or model alias is not correct" << endl;
printAliases(zooFile);
return -1;
}
confThreshold = parser.get<float>("thr");
nmsThreshold = parser.get<float>("nms");
float scale = parser.get<float>("scale");
Scalar mean = parser.get<Scalar>("mean");
bool swapRB = parser.get<bool>("rgb");
int inpWidth = parser.get<int>("width");
int inpHeight = parser.get<int>("height");
size_t asyncNumReq = parser.get<int>("async");
CV_Assert(parser.has("model"));
std::string modelPath = findFile(parser.get<String>("model"));
std::string configPath = findFile(parser.get<String>("config"));
//![preprocess_params]
scale = parser.get<float>("scale");
meanv = parser.get<Scalar>("mean");
swapRB = parser.get<bool>("rgb");
inpWidth = parser.get<int>("width");
inpHeight = parser.get<int>("height");
int async = parser.get<int>("async");
paddingValue = parser.get<float>("padvalue");
const string yolo_name = parser.get<String>("postprocessing");
paddingMode = static_cast<ImagePaddingMode>(parser.get<int>("paddingmode"));
//![preprocess_params]
String sha1 = parser.get<String>("sha1");
const string modelPath = findModel(parser.get<String>("model"), sha1);
const string configPath = findFile(parser.get<String>("config"));
framework = modelPath.substr(modelPath.rfind('.') + 1);
// Open file with classes names.
if (parser.has("classes"))
if (parser.has("labels"))
{
std::string file = parser.get<String>("classes");
std::ifstream ifs(file.c_str());
const string file = findFile(parser.get<String>("labels"));
ifstream ifs(file.c_str());
if (!ifs.is_open())
CV_Error(Error::StsError, "File " + file + " not found");
std::string line;
while (std::getline(ifs, line))
string line;
while (getline(ifs, line))
{
classes.push_back(line);
labels.push_back(line);
}
}
// Load a model.
Net net = readNet(modelPath, configPath, parser.get<String>("framework"));
int backend = parser.get<int>("backend");
//![read_net]
Net net = readNet(modelPath, configPath);
int backend = getBackendID(parser.get<String>("backend"));
net.setPreferableBackend(backend);
net.setPreferableTarget(parser.get<int>("target"));
std::vector<String> outNames = net.getUnconnectedOutLayersNames();
net.setPreferableTarget(getTargetID(parser.get<String>("target")));
//![read_net]
// Create a window
static const std::string kWinName = "Deep learning object detection in OpenCV";
namedWindow(kWinName, WINDOW_NORMAL);
static const string kWinName = "Deep learning object detection in OpenCV";
namedWindow(kWinName, WINDOW_AUTOSIZE);
int initialConf = (int)(confThreshold * 100);
createTrackbar("Confidence threshold, %", kWinName, &initialConf, 99, callback);
createTrackbar("Confidence threshold, %", kWinName, &initialConf, 99, callback, &net);
// Open a video file or an image file or a camera stream.
VideoCapture cap;
if (parser.has("input"))
cap.open(parser.get<String>("input"));
else
cap.open(parser.get<int>("device"));
bool openSuccess = parser.has("input") ? cap.open(parser.get<String>("input")) : cap.open(parser.get<int>("device"));
if (!openSuccess){
cout << "Could not open input file or camera device" << endl;
return 0;
}
#ifdef USE_THREADS
bool process = true;
FontFace sans("sans");
// Frames capturing thread
QueueFPS<Mat> framesQueue;
std::thread framesThread([&](){
Mat frame;
while (process)
{
cap >> frame;
if (!frame.empty())
framesQueue.push(frame.clone());
else
break;
}
});
int stdSize = 15;
int stdWeight = 150;
int stdImgSize = 512;
int stdThickness = 2;
vector<int> classIds;
vector<float> confidences;
vector<Rect> boxes;
// Frames processing thread
QueueFPS<Mat> processedFramesQueue;
QueueFPS<std::vector<Mat> > predictionsQueue;
std::thread processingThread([&](){
std::queue<AsyncArray> futureOutputs;
Mat blob;
while (process)
{
// Get a next frame
if (async > 0 && backend == DNN_BACKEND_INFERENCE_ENGINE){
asyncNumReq = async;
}
if (async != 0) {
// Threading is enabled
bool process = true;
// Frames capturing thread
QueueFPS<Mat> framesQueue;
std::thread framesThread([&]() {
Mat frame;
{
if (!framesQueue.empty())
{
frame = framesQueue.get();
if (asyncNumReq)
{
if (futureOutputs.size() == asyncNumReq)
frame = Mat();
}
else
framesQueue.clear(); // Skip the rest of frames
}
}
// Process the frame
if (!frame.empty())
{
preprocess(frame, net, Size(inpWidth, inpHeight), scale, mean, swapRB);
processedFramesQueue.push(frame);
if (asyncNumReq)
{
futureOutputs.push(net.forwardAsync());
}
while (process) {
cap >> frame;
if (!frame.empty())
framesQueue.push(frame.clone());
else
break;
}
});
// Frames processing thread
QueueFPS<Mat> processedFramesQueue;
QueueFPS<std::vector<Mat>> predictionsQueue;
std::thread processingThread([&]() {
std::queue<AsyncArray> futureOutputs;
Mat blob;
while (process) {
// Get the next frame
Mat frame;
{
std::vector<Mat> outs;
net.forward(outs, outNames);
predictionsQueue.push(outs);
if (!framesQueue.empty()) {
frame = framesQueue.get();
if (asyncNumReq) {
if (futureOutputs.size() == asyncNumReq)
frame = Mat();
}
}
}
// Process the frame
if (!frame.empty()) {
preprocess(frame, net, Size(inpWidth, inpHeight));
processedFramesQueue.push(frame);
if (asyncNumReq) {
futureOutputs.push(net.forwardAsync());
} else {
vector<Mat> outs;
net.forward(outs, net.getUnconnectedOutLayersNames());
predictionsQueue.push(outs);
}
}
while (!futureOutputs.empty() &&
futureOutputs.front().wait_for(std::chrono::seconds(0))) {
AsyncArray async_out = futureOutputs.front();
futureOutputs.pop();
Mat out;
async_out.get(out);
predictionsQueue.push({out});
}
}
});
while (!futureOutputs.empty() &&
futureOutputs.front().wait_for(std::chrono::seconds(0)))
{
AsyncArray async_out = futureOutputs.front();
futureOutputs.pop();
Mat out;
async_out.get(out);
predictionsQueue.push({out});
// Postprocessing and rendering loop
while (waitKey(100) < 0) {
if (predictionsQueue.empty())
continue;
vector<Mat> outs = predictionsQueue.get();
Mat frame = processedFramesQueue.get();
classIds.clear();
confidences.clear();
boxes.clear();
postprocess(frame, outs, net, backend, classIds, confidences, boxes, yolo_name);
drawPred(classIds, confidences, boxes, frame, sans, stdSize, stdWeight, stdImgSize, stdThickness);
int imgWidth = max(frame.rows, frame.cols);
int size = static_cast<int>((stdSize * imgWidth) / (stdImgSize * 1.5));
int weight = static_cast<int>((stdWeight * imgWidth) / (stdImgSize * 1.5));
if (predictionsQueue.counter > 1) {
string label = format("Camera: %.2f FPS", framesQueue.getFPS());
rectangle(frame, Point(0, 0), Point(10 * size, 3 * size + size / 4), Scalar::all(255), FILLED);
putText(frame, label, Point(0, size), Scalar::all(0), sans, size, weight);
label = format("Network: %.2f FPS", predictionsQueue.getFPS());
putText(frame, label, Point(0, 2 * size), Scalar::all(0), sans, size, weight);
label = format("Skipped frames: %d", framesQueue.counter - predictionsQueue.counter);
putText(frame, label, Point(0, 3 * size), Scalar::all(0), sans, size, weight);
}
imshow(kWinName, frame);
}
});
// Postprocessing and rendering loop
while (waitKey(1) < 0)
{
if (predictionsQueue.empty())
continue;
process = false;
framesThread.join();
processingThread.join();
} else {
if (asyncNumReq)
CV_Error(Error::StsNotImplemented, "Asynchronous forward is supported only with Inference Engine backend.");
// Threading is disabled, run synchronously
Mat frame, blob;
while (waitKey(100) < 0) {
cap >> frame;
if (frame.empty()) {
waitKey();
break;
}
preprocess(frame, net, Size(inpWidth, inpHeight));
std::vector<Mat> outs = predictionsQueue.get();
Mat frame = processedFramesQueue.get();
vector<Mat> outs;
net.forward(outs, net.getUnconnectedOutLayersNames());
postprocess(frame, outs, net, backend);
classIds.clear();
confidences.clear();
boxes.clear();
if (predictionsQueue.counter > 1)
{
std::string label = format("Camera: %.2f FPS", framesQueue.getFPS());
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
postprocess(frame, outs, net, backend, classIds, confidences, boxes, yolo_name);
label = format("Network: %.2f FPS", predictionsQueue.getFPS());
putText(frame, label, Point(0, 30), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
drawPred(classIds, confidences, boxes, frame, sans, stdSize, stdWeight, stdImgSize, stdThickness);
label = format("Skipped frames: %d", framesQueue.counter - predictionsQueue.counter);
putText(frame, label, Point(0, 45), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
vector<double> layersTimes;
int imgWidth = max(frame.rows, frame.cols);
int size = static_cast<int>((stdSize * imgWidth) / (stdImgSize * 1.5));
int weight = static_cast<int>((stdWeight * imgWidth) / (stdImgSize * 1.5));
double freq = getTickFrequency() / 1000;
double t = net.getPerfProfile(layersTimes) / freq;
string label = format("Inference time: %.2f ms", t);
putText(frame, label, Point(0, size), Scalar(0, 255, 0), sans, size, weight);
imshow(kWinName, frame);
}
imshow(kWinName, frame);
}
process = false;
framesThread.join();
processingThread.join();
#else // USE_THREADS
if (asyncNumReq)
CV_Error(Error::StsNotImplemented, "Asynchronous forward is supported only with Inference Engine backend.");
// Process frames.
Mat frame, blob;
while (waitKey(1) < 0)
{
cap >> frame;
if (frame.empty())
{
waitKey();
break;
}
preprocess(frame, net, Size(inpWidth, inpHeight), scale, mean, swapRB);
std::vector<Mat> outs;
net.forward(outs, outNames);
postprocess(frame, outs, net, backend);
// Put efficiency information.
std::vector<double> layersTimes;
double freq = getTickFrequency() / 1000;
double t = net.getPerfProfile(layersTimes) / freq;
std::string label = format("Inference time: %.2f ms", t);
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
imshow(kWinName, frame);
}
#endif // USE_THREADS
return 0;
}
inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
const Scalar& mean, bool swapRB)
void preprocess(const Mat& frame, Net& net, Size inpSize)
{
static Mat blob;
// Create a 4D blob from a frame.
if (inpSize.width <= 0) inpSize.width = frame.cols;
if (inpSize.height <= 0) inpSize.height = frame.rows;
blobFromImage(frame, blob, 1.0, inpSize, Scalar(), swapRB, false, CV_8U);
Size size(inpSize.width <= 0 ? frame.cols : inpSize.width, inpSize.height <= 0 ? frame.rows : inpSize.height);
// Run a model.
net.setInput(blob, "", scale, mean);
if (net.getLayer(0)->outputNameToIndex("im_info") != -1) // Faster-RCNN or R-FCN
// Prepare the blob from the image
Mat inp;
if(framework == "weights"){ // checks whether model is darknet
blobFromImage(frame, inp, scale, size, meanv, swapRB, false, CV_32F);
}
else{
//![preprocess_call]
Image2BlobParams imgParams(
scale,
size,
meanv,
swapRB,
CV_32F,
DNN_LAYOUT_NCHW,
paddingMode,
paddingValue);
inp = blobFromImageWithParams(frame, imgParams);
//![preprocess_call]
}
// Set the blob as the network input
net.setInput(inp);
// Check if the model is Faster-RCNN or R-FCN
if (net.getLayer(0)->outputNameToIndex("im_info") != -1)
{
resize(frame, frame, inpSize);
Mat imInfo = (Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
// Resize the frame and prepare imInfo
resize(frame, frame, size);
Mat imInfo = (Mat_<float>(1, 3) << size.height, size.width, 1.6f);
net.setInput(imInfo, "im_info");
}
}
void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net, int backend)
void yoloPostProcessing(
const vector<Mat>& outs,
vector<int>& keep_classIds,
vector<float>& keep_confidences,
vector<Rect2d>& keep_boxes,
float conf_threshold,
float iou_threshold,
const string& yolo_name)
{
static std::vector<int> outLayers = net.getUnconnectedOutLayers();
static std::string outLayerType = net.getLayer(outLayers[0])->type;
// Retrieve
vector<int> classIds;
vector<float> confidences;
vector<Rect2d> boxes;
vector<Mat> outs_copy = outs;
if (yolo_name == "yolov8")
{
transposeND(outs_copy[0], {0, 2, 1}, outs_copy[0]);
}
if (yolo_name == "yolonas")
{
// outs contains 2 elements of shape [1, 8400, 80] and [1, 8400, 4]. Concat them to get [1, 8400, 84]
Mat concat_out;
// squeeze the first dimension
outs_copy[0] = outs_copy[0].reshape(1, outs_copy[0].size[1]);
outs_copy[1] = outs_copy[1].reshape(1, outs_copy[1].size[1]);
hconcat(outs_copy[1], outs_copy[0], concat_out);
outs_copy[0] = concat_out;
// remove the second element
outs_copy.pop_back();
// unsqueeze the first dimension
outs_copy[0] = outs_copy[0].reshape(0, vector<int>{1, 8400, 84});
}
for (auto preds : outs_copy)
{
preds = preds.reshape(1, preds.size[1]); // [1, 8400, 85] -> [8400, 85]
for (int i = 0; i < preds.rows; ++i)
{
// filter out non-object
float obj_conf = (yolo_name == "yolov8" || yolo_name == "yolonas") ? 1.0f : preds.at<float>(i, 4);
if (obj_conf < conf_threshold)
continue;
Mat scores = preds.row(i).colRange((yolo_name == "yolov8" || yolo_name == "yolonas") ? 4 : 5, preds.cols);
double conf;
Point maxLoc;
minMaxLoc(scores, 0, &conf, 0, &maxLoc);
conf = (yolo_name == "yolov8" || yolo_name == "yolonas") ? conf : conf * obj_conf;
if (conf < conf_threshold)
continue;
// get bbox coords
float* det = preds.ptr<float>(i);
double cx = det[0];
double cy = det[1];
double w = det[2];
double h = det[3];
// [x1, y1, x2, y2]
if (yolo_name == "yolonas") {
boxes.push_back(Rect2d(cx, cy, w, h));
} else {
boxes.push_back(Rect2d(cx - 0.5 * w, cy - 0.5 * h,
cx + 0.5 * w, cy + 0.5 * h));
}
classIds.push_back(maxLoc.x);
confidences.push_back(static_cast<float>(conf));
}
}
// NMS
vector<int> keep_idx;
NMSBoxes(boxes, confidences, conf_threshold, iou_threshold, keep_idx);
for (auto i : keep_idx)
{
keep_classIds.push_back(classIds[i]);
keep_confidences.push_back(confidences[i]);
keep_boxes.push_back(boxes[i]);
}
}
void postprocess(Mat& frame, const vector<Mat>& outs, Net& net, int backend, vector<int>& classIds, vector<float>& confidences, vector<Rect>& boxes, const string yolo_name)
{
static vector<int> outLayers = net.getUnconnectedOutLayers();
static string outLayerType = net.getLayer(outLayers[0])->type;
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<Rect> boxes;
if (outLayerType == "DetectionOutput")
{
// Network produces output blob with a shape 1x1xNx7 where N is a number of
@@ -405,14 +580,46 @@ void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net, int backend
}
}
}
else
CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType);
else if (outLayerType == "Identity")
{
//![forward_buffers]
vector<int> keep_classIds;
vector<float> keep_confidences;
vector<Rect2d> keep_boxes;
//![forward_buffers]
// NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample
// or NMS is required if number of outputs > 1
//![postprocess]
yoloPostProcessing(outs, keep_classIds, keep_confidences, keep_boxes, confThreshold, nmsThreshold, yolo_name);
//![postprocess]
for (size_t i = 0; i < keep_classIds.size(); ++i)
{
classIds.push_back(keep_classIds[i]);
confidences.push_back(keep_confidences[i]);
Rect2d box = keep_boxes[i];
boxes.push_back(Rect(cvFloor(box.x), cvFloor(box.y), cvFloor(box.width-box.x), cvFloor(box.height-box.y)));
}
if (framework == "onnx"){
Image2BlobParams paramNet;
paramNet.scalefactor = scale;
paramNet.size = Size(inpWidth, inpHeight);
paramNet.mean = meanv;
paramNet.swapRB = swapRB;
paramNet.paddingmode = paddingMode;
paramNet.blobRectsToImageRects(boxes, boxes, frame.size());
}
}
else
{
CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType);
}
// NMS is used inside Region layer only on DNN_BACKEND_OPENCV for other backends we need NMS in sample
// or NMS is required if the number of outputs > 1
if (outLayers.size() > 1 || (outLayerType == "Region" && backend != DNN_BACKEND_OPENCV))
{
std::map<int, std::vector<size_t> > class2indices;
map<int, vector<size_t> > class2indices;
for (size_t i = 0; i < classIds.size(); i++)
{
if (confidences[i] >= confThreshold)
@@ -420,20 +627,20 @@ void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net, int backend
class2indices[classIds[i]].push_back(i);
}
}
std::vector<Rect> nmsBoxes;
std::vector<float> nmsConfidences;
std::vector<int> nmsClassIds;
for (std::map<int, std::vector<size_t> >::iterator it = class2indices.begin(); it != class2indices.end(); ++it)
vector<Rect> nmsBoxes;
vector<float> nmsConfidences;
vector<int> nmsClassIds;
for (map<int, vector<size_t> >::iterator it = class2indices.begin(); it != class2indices.end(); ++it)
{
std::vector<Rect> localBoxes;
std::vector<float> localConfidences;
std::vector<size_t> classIndices = it->second;
vector<Rect> localBoxes;
vector<float> localConfidences;
vector<size_t> classIndices = it->second;
for (size_t i = 0; i < classIndices.size(); i++)
{
localBoxes.push_back(boxes[classIndices[i]]);
localConfidences.push_back(confidences[classIndices[i]]);
}
std::vector<int> nmsIndices;
vector<int> nmsIndices;
NMSBoxes(localBoxes, localConfidences, confThreshold, nmsThreshold, nmsIndices);
for (size_t i = 0; i < nmsIndices.size(); i++)
{
@@ -447,36 +654,49 @@ void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net, int backend
classIds = nmsClassIds;
confidences = nmsConfidences;
}
for (size_t idx = 0; idx < boxes.size(); ++idx)
{
Rect box = boxes[idx];
drawPred(classIds[idx], confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
}
}
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
void drawPred(vector<int>& classIds, vector<float>& confidences, vector<Rect>& boxes, Mat& frame, FontFace& sans, int stdSize, int stdWeight, int stdImgSize, int stdThickness)
{
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0));
int imgWidth = max(frame.rows, frame.cols);
int size = (stdSize*imgWidth)/stdImgSize;
int weight = (stdWeight*imgWidth)/stdImgSize;
int thickness = (stdThickness*imgWidth)/stdImgSize;
std::string label = format("%.2f", conf);
if (!classes.empty())
{
CV_Assert(classId < (int)classes.size());
label = classes[classId] + ": " + label;
for (size_t idx = 0; idx < boxes.size(); ++idx){
Scalar boxColor = getColor(classIds[idx]);
int left = boxes[idx].x;
int top = boxes[idx].y;
int right = boxes[idx].x + boxes[idx].width;
int bottom = boxes[idx].y + boxes[idx].height;
rectangle(frame, Point(left, top), Point(right, bottom), boxColor, thickness);
string label = format("%.2f", confidences[idx]);
if (!labels.empty())
{
CV_Assert(classIds[idx] < (int)labels.size());
label = labels[classIds[idx]] + ": " + label;
}
Rect r = getTextSize(Size(), label, Point(), sans, size, weight);
int baseline = r.y + r.height;
Size labelSize = Size(r.width, r.height + size/4 - baseline);
top = max(top-thickness/2, labelSize.height);
rectangle(frame, Point(left-thickness/2, top-(labelSize.height)),
Point(left + labelSize.width, top), boxColor, FILLED);
putText(frame, label, Point(left, top-size/4), getTextColor(boxColor), sans, size, weight);
}
int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
top = max(top, labelSize.height);
rectangle(frame, Point(left, top - labelSize.height),
Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar());
}
void callback(int pos, void*)
{
confThreshold = pos * 0.01f;
}
Scalar getColor(int classId) {
int r = min((classId >> 0 & 1) * 128 + (classId >> 3 & 1) * 64 + (classId >> 6 & 1) * 32 + 80, 255);
int g = min((classId >> 1 & 1) * 128 + (classId >> 4 & 1) * 64 + (classId >> 7 & 1) * 32 + 40, 255);
int b = min((classId >> 2 & 1) * 128 + (classId >> 5 & 1) * 64 + (classId >> 8 & 1) * 32 + 40, 255);
return Scalar(b, g, r);
}