File size: 1,987 Bytes
4249ce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace cv;

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", "");

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

    Mat rgb;
    cvtColor(img, rgb, COLOR_BGR2RGB);
    resize(rgb, rgb, Size(224, 224));
    rgb.convertTo(rgb, CV_32F);

    int dims[] = {1, 224, 224, 3};
    Mat blob(4, dims, CV_32F, rgb.data);

    dnn::Net net = dnn::readNet(model);
    net.setInput(blob);
    Mat scores = net.forward().reshape(1, 1);

    Point classId;
    double conf;
    minMaxLoc(scores, 0, &conf, 0, &classId);

    std::string label = std::to_string(classId.x);
    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 (classId.x < (int)names.size()) label = names[classId.x];
    }

    std::cout << "class " << classId.x << " " << label << " confidence " << conf << std::endl;

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