File size: 2,204 Bytes
e9eb33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <algorithm>
#include <array>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

static std::string argVal(int argc, char** argv, const std::string& key, const std::string& def)
{
    for (int i = 1; i + 1 < argc; ++i)
        if (key == argv[i]) return argv[i + 1];
    return def;
}

int main(int argc, char** argv)
{
    std::string model  = argVal(argc, argv, "--model",  "tensorflow_inception_graph_2026jul.onnx");
    std::string image  = argVal(argc, argv, "--image",  "example_outputs/input_image.png");
    std::string output = argVal(argc, argv, "--output", "example_outputs/output_image.png");
    std::string labels = argVal(argc, argv, "--labels", "");

    cv::Mat img = cv::imread(image);
    if (img.empty())
    {
        std::cerr << "could not read image: " << image << std::endl;
        return 1;
    }

    cv::Mat rgb;
    cv::cvtColor(img, rgb, cv::COLOR_BGR2RGB);
    cv::resize(rgb, rgb, cv::Size(224, 224));
    rgb.convertTo(rgb, CV_32F);
    if (!rgb.isContinuous()) rgb = rgb.clone();

    int blobShape[] = {1, 224, 224, 3};
    cv::Mat blob(4, blobShape, CV_32F, rgb.data);
    cv::dnn::Net net = cv::dnn::readNetFromONNX(model);
    net.setInput(blob);
    cv::Mat scoresMat = net.forward();
    float* scores = (float*)scoresMat.data;
    int n = (int)scoresMat.total();
    int top = (int)(std::max_element(scores, scores + n) - scores);
    float conf = scores[top];

    std::string label = std::to_string(top);
    if (!labels.empty())
    {
        std::ifstream f(labels);
        std::vector<std::string> names;
        std::string line;
        while (std::getline(f, line)) names.push_back(line);
        if (top < (int)names.size()) label = names[top];
    }
    std::cout << "class " << top << " " << label << " confidence " << conf << std::endl;

    cv::Mat out = img.clone();
    cv::putText(out, cv::format("%s (%.2f)", label.c_str(), conf), cv::Point(10, 30),
                cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 255, 0), 2);
    cv::imwrite(output, out);
    std::cout << "wrote " << output << std::endl;
    return 0;
}