this is my code in cpp but nothung detected "#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
code
cv::dnn::Net net = cv::dnn::readNetFromONNX("best.onnx");
net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
cv::Mat image = cv::imread("00.jpg");
if (image.empty())
{
std::cerr << "Could not read the image!" << std::endl;
return -1;
}
cv::Mat blob;
int inputWidth = 640;
int inputHeight = 640;
cv::dnn::blobFromImage(image, blob, 1 / 255.0, cv::Size(640, 640), cv::Scalar(0, 0, 0), true, false);
net.setInput(blob);
std::vector<cv::Mat> outputs;
net.forward(outputs, net.getUnconnectedOutLayersNames());
std::vector<std::string> layerNames = net.getUnconnectedOutLayersNames();
std::cout << "Unconnected Output Layers:" << std::endl;
for (const auto &name : layerNames)
std::cout << name << std::endl;
std::cout << "Output Shape:" << std::endl;
float confThreshold = 0.5;
for (const auto &output : outputs)
{
for (int i = 0; i < output.rows; ++i)
{
float confidence = output.at<float>(i, 4);
if (confidence > confThreshold)
{
float x = output.at<float>(i, 0) * image.cols;
float y = output.at<float>(i, 1) * image.rows;
float width = output.at<float>(i, 2) * image.cols;
float height = output.at<float>(i, 3) * image.rows;
int classId = static_cast<int>(output.at<float>(i, 5));
cv::rectangle(image, cv::Point(x, y), cv::Point(x + width, y + height), cv::Scalar(0, 255, 0), 2);
std::string label = cv::format("Class %d: %.2f", classId, confidence);
cv::putText(image, label, cv::Point(x, y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
}
}
}
// Display image with detections
cv::namedWindow("Detections", 0);
cv::imshow("Detections", image);
cv::waitKey(0);
return 0;
Assistant
User
give me complate code no explain needed
Assistant
cpp
}
"
The code you provided is a C++ implementation for object detection using OpenCV's Deep Neural Network (DNN) module. However, there might be several reasons why "nothing is detected" when running the program. I will go through potential issues and their fixes:
1. Incorrect .onnx Model Input/Output Format:
Your ONNX model might not be compatible with how you are preprocessing the input (blobFromImage()) or how you are parsing the outputs. Check these:
Input Dimensions: Ensure that the model expects inputs of size (1, 3, 640, 640) (1 batch, 3 color channels, 640x640 spatial dimensions). If the expected size is different, adjust the width/height in blobFromImage, e.g., cv::Size(320, 320) for 320x320 models.
Output Format: ONNX models can have different output formats depending on the architecture (e.g., YOLO, SSD). The parsing logic inside the loop may not align with your model's output format. You are assuming YOLO-style outputs, but double-check the format your model uses by referring to your best.onnx model's details.
Fix:
Use an ONNX model viewer (e.g., Netron: https://netron.app/) to inspect your model's input/output shapes and layer names. Update the code to align with those.
2. Class ID and Confidence Parsing:
You are treating the 6th element (output.at<float>(i, 5)) as the classId. However, this depends on your ONNX model structure:
Many models (like YOLOv5/YOLOv8) use the format [x_center, y_center, width, height, confidence, class probabilities...], where the confidence score is at index 4 and class probabilities start at 5.
If your model outputs probabilities instead of direct class IDs, choose the class with the maximum probability.
Fix logic for confidence and class ID extraction:
cpp
const int classIdOffset = 5; // Assuming scores start at index 5
float confidence = output.at<float>(i, 4);
if (confidence > confThreshold)
{
// Find the class with the highest probability
cv::Mat scores = output.row(i).colRange(classIdOffset, output.cols);
cv::Point classIdPoint;
double maxClassScore;
cv::minMaxLoc(scores, 0, &maxClassScore, 0, &classIdPoint);
confidence = static_cast<float>(maxClassScore);
int classId = classIdPoint.x;
// Calculate bounding box
float x = output.at<float>(i, 0) * image.cols;
float y = output.at<float>(i, 1) * image.rows;
float width = output.at<float>(i, 2) * image.cols;
float height = output.at<float>(i, 3) * image.rows;
// Draw rectangle and label
cv::rectangle(image, cv::Point(x - width / 2, y - height / 2), cv::Point(x + width / 2, y + height / 2), cv::Scalar(0, 255, 0), 2);
std::string label = cv::format("Class %d: %.2f", classId, confidence);
cv::putText(image, label, cv::Point(x - width / 2, y - height / 2 - 10), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
}
3. ONNX Model Configuration:
If the ONNX model is trained with normalization requirements (e.g., mean subtraction, scaling), you need to ensure the input matches the requirements:
Your blobFromImage() uses 1 / 255.0 normalization. If the model was trained on images normalized differently (e.g., with mean subtraction [0.485, 0.456, 0.406] and standard deviation [0.229, 0.224, 0.225]), you must replicate that:
cpp
cv::Scalar mean = cv::Scalar(0.485, 0.456, 0.406); // Example mean
cv::Scalar std = cv::Scalar(0.229, 0.224, 0.225); // Example std
cv::Mat blob = cv::dnn::blobFromImage(image, 1 / 255.0, cv::Size(640, 640), mean, true, false);
Check your model's documentation or training pipeline for the correct preprocessing pipeline.
4. Output Layers Issue:
net.getUnconnectedOutLayersNames() returns layer names, but it's possible that the output layer configuration is incorrect for your model. Debugging this:
Print the output layer names and manually verify they match the expected prediction layers of your ONNX model's architecture.
Add this debug output:
cpp
std::vector<std::string> layerNames = net.getLayerNames();
for (int i = 0; i < layerNames.size(); ++i)
std::cout << "Layer " << i << ": " << layerNames[i] << std::endl;
Verify that getUnconnectedOutLayersNames() returns only prediction layers (not intermediate computation layers).
5. General Debugging Steps:
File Existence: Ensure the files best.onnx and 00.jpg are in the same directory as your executable, or provide absolute paths.
Image Format: Ensure 00.jpg is a valid image and not corrupted.
ONNX Runtime Errors: Enable verbose mode to see ONNX parsing issues:
for (const auto &output : outputs)
{
std::cout << "Output size: " << output.size << std::endl;
}
6. Visualization Issues:
If the detections are working but not visualized correctly:
Ensure bounding boxes are drawn with correct coordinates.
If normalized coordinates are used (e.g., values between 0 and 1), the bounding box calculation should scale appropriately for the original image size.
Recommended Adjustments:
Here's a revised snippet for the loop processing detections:
cpp
for (const auto &output : outputs)
{
for (int i = 0; i < output.rows; ++i)
{
float confidence = output.at<float>(i, 4); // Confidence score
if (confidence > confThreshold)
{
// Extract box coordinates (cx, cy, width, height)
float cx = output.at<float>(i, 0) * image.cols;
float cy = output.at<float>(i, 1) * image.rows;
float w = output.at<float>(i, 2) * image.cols;
float h = output.at<float>(i, 3) * image.rows;
// Convert center-based coordinates to top-left corner coordinates
float x = cx - w / 2.0f;
float y = cy - h / 2.0f;
// Extract class scores
cv::Mat scores = output.row(i).colRange(5, output.cols);
cv::Point classIdPoint;
double maxClassScore;
cv::minMaxLoc(scores, 0, &maxClassScore, 0, &classIdPoint);
int classId = classIdPoint.x;
confidence = static_cast<float>(maxClassScore);
// Draw the bounding box and label on the image
cv::rectangle(image, cv::Point(x, y), cv::Point(x + w, y + h), cv::Scalar(0, 255, 0), 2);
std::string label = cv::format("Class %d: %.2f", classId, confidence);
cv::putText(image, label, cv::Point(x, y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
}
}
}
Conclusion:
Verify the model input and output preprocessing/mapping.
Use normalized scores, and ensure class IDs are extracted correctly.
Modify preprocessing settings to match the ONNX model's requirements.
Debug outputs of each step for further insights.
Make the adjustments above and let me know if the problem persists!
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
#include <vector>
#include <string>
int main()
{
// Load ONNX model
cv::dnn::Net net = cv::dnn::readNetFromONNX("best.onnx");
net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
// Load input image
cv::Mat image = cv::imread("00.jpg");
if (image.empty())
{
std::cerr << "Could not read the image!" << std::endl;
return -1;
}
// Preprocess the image (blob creation)
cv::Mat blob;
int inputWidth = 640;
int inputHeight = 640;
cv::dnn::blobFromImage(image, blob, 1 / 255.0, cv::Size(inputWidth, inputHeight), cv::Scalar(0, 0, 0), true, false);
net.setInput(blob);
// Perform forward pass
std::vector<cv::Mat> outputs;
net.forward(outputs, net.getUnconnectedOutLayersNames());
// Post-processing
float confThreshold = 0.5;
for (const auto &output : outputs)
{
for (int i = 0; i < output.rows; ++i)
{
float confidence = output.at<float>(i, 4);
if (confidence > confThreshold)
{
// Get bounding box coordinates and class ID
float cx = output.at<float>(i, 0) * image.cols;
float cy = output.at<float>(i, 1) * image.rows;
float w = output.at<float>(i, 2) * image.cols;
float h = output.at<float>(i, 3) * image.rows;
float x = cx - w / 2.0f;
float y = cy - h / 2.0f;
cv::Mat scores = output.row(i).colRange(5, output.cols);
cv::Point classIdPoint;
double maxClassScore;
cv::minMaxLoc(scores, 0, &maxClassScore, 0, &classIdPoint);
int classId = classIdPoint.x;
confidence = static_cast<float>(maxClassScore);
// Draw bounding box and label
cv::rectangle(image, cv::Point(x, y), cv::Point(x + w, y + h), cv::Scalar(0, 255, 0), 2);
std::string label = cv::format("Class %d: %.2f", classId, confidence);
cv::putText(image, label, cv::Point(x, y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
}
}
}
// Display image with detections
cv::namedWindow("Detections", 0);
cv::imshow("Detections", image);
cv::waitKey(0);
return 0;
}