inference.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #include "inference.h"
  2. Inference::Inference(const std::string &onnxModelPath, const cv::Size &modelInputShape, const std::string &classesTxtFile, const bool &runWithCuda)
  3. {
  4. modelPath = onnxModelPath;
  5. modelShape = modelInputShape;
  6. classesPath = classesTxtFile;
  7. cudaEnabled = runWithCuda;
  8. loadOnnxNetwork();
  9. // loadClassesFromFile(); The classes are hard-coded for this example
  10. }
  11. std::vector<Detection> Inference::runInference(const cv::Mat &input)
  12. {
  13. cv::Mat modelInput = input;
  14. if (letterBoxForSquare && modelShape.width == modelShape.height)
  15. modelInput = formatToSquare(modelInput);
  16. cv::Mat blob;
  17. cv::dnn::blobFromImage(modelInput, blob, 1.0/255.0, modelShape, cv::Scalar(), true, false);
  18. net.setInput(blob);
  19. std::vector<cv::Mat> outputs;
  20. net.forward(outputs, net.getUnconnectedOutLayersNames());
  21. int rows = outputs[0].size[1];
  22. int dimensions = outputs[0].size[2];
  23. bool yolov8 = false;
  24. // yolov5 has an output of shape (batchSize, 25200, 85) (Num classes + box[x,y,w,h] + confidence[c])
  25. // yolov8 has an output of shape (batchSize, 84, 8400) (Num classes + box[x,y,w,h])
  26. if (dimensions > rows) // Check if the shape[2] is more than shape[1] (yolov8)
  27. {
  28. yolov8 = true;
  29. rows = outputs[0].size[2];
  30. dimensions = outputs[0].size[1];
  31. outputs[0] = outputs[0].reshape(1, dimensions);
  32. cv::transpose(outputs[0], outputs[0]);
  33. }
  34. float *data = (float *)outputs[0].data;
  35. float x_factor = modelInput.cols / modelShape.width;
  36. float y_factor = modelInput.rows / modelShape.height;
  37. std::vector<int> class_ids;
  38. std::vector<float> confidences;
  39. std::vector<cv::Rect> boxes;
  40. for (int i = 0; i < rows; ++i)
  41. {
  42. if (yolov8)
  43. {
  44. float *classes_scores = data+4;
  45. cv::Mat scores(1, classes.size(), CV_32FC1, classes_scores);
  46. cv::Point class_id;
  47. double maxClassScore;
  48. minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);
  49. if (maxClassScore > modelScoreThreshold)
  50. {
  51. confidences.push_back(maxClassScore);
  52. class_ids.push_back(class_id.x);
  53. float x = data[0];
  54. float y = data[1];
  55. float w = data[2];
  56. float h = data[3];
  57. int left = int((x - 0.5 * w) * x_factor);
  58. int top = int((y - 0.5 * h) * y_factor);
  59. int width = int(w * x_factor);
  60. int height = int(h * y_factor);
  61. boxes.push_back(cv::Rect(left, top, width, height));
  62. }
  63. }
  64. else // yolov5
  65. {
  66. float confidence = data[4];
  67. if (confidence >= modelConfidenceThreshold)
  68. {
  69. float *classes_scores = data+5;
  70. cv::Mat scores(1, classes.size(), CV_32FC1, classes_scores);
  71. cv::Point class_id;
  72. double max_class_score;
  73. minMaxLoc(scores, 0, &max_class_score, 0, &class_id);
  74. if (max_class_score > modelScoreThreshold)
  75. {
  76. confidences.push_back(confidence);
  77. class_ids.push_back(class_id.x);
  78. float x = data[0];
  79. float y = data[1];
  80. float w = data[2];
  81. float h = data[3];
  82. int left = int((x - 0.5 * w) * x_factor);
  83. int top = int((y - 0.5 * h) * y_factor);
  84. int width = int(w * x_factor);
  85. int height = int(h * y_factor);
  86. boxes.push_back(cv::Rect(left, top, width, height));
  87. }
  88. }
  89. }
  90. data += dimensions;
  91. }
  92. std::vector<int> nms_result;
  93. cv::dnn::NMSBoxes(boxes, confidences, modelScoreThreshold, modelNMSThreshold, nms_result);
  94. std::vector<Detection> detections{};
  95. for (unsigned long i = 0; i < nms_result.size(); ++i)
  96. {
  97. int idx = nms_result[i];
  98. Detection result;
  99. result.class_id = class_ids[idx];
  100. result.confidence = confidences[idx];
  101. std::random_device rd;
  102. std::mt19937 gen(rd());
  103. std::uniform_int_distribution<int> dis(100, 255);
  104. result.color = cv::Scalar(dis(gen),
  105. dis(gen),
  106. dis(gen));
  107. result.className = classes[result.class_id];
  108. result.box = boxes[idx];
  109. detections.push_back(result);
  110. }
  111. return detections;
  112. }
  113. void Inference::loadClassesFromFile()
  114. {
  115. std::ifstream inputFile(classesPath);
  116. if (inputFile.is_open())
  117. {
  118. std::string classLine;
  119. while (std::getline(inputFile, classLine))
  120. classes.push_back(classLine);
  121. inputFile.close();
  122. }
  123. }
  124. void Inference::loadOnnxNetwork()
  125. {
  126. net = cv::dnn::readNetFromONNX(modelPath);
  127. if (cudaEnabled)
  128. {
  129. net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
  130. net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
  131. }
  132. else
  133. {
  134. net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
  135. net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
  136. }
  137. }
  138. cv::Mat Inference::formatToSquare(const cv::Mat &source)
  139. {
  140. int col = source.cols;
  141. int row = source.rows;
  142. int _max = MAX(col, row);
  143. cv::Mat result = cv::Mat::zeros(_max, _max, CV_8UC3);
  144. source.copyTo(result(cv::Rect(0, 0, col, row)));
  145. return result;
  146. }