File: image_classification.cpp

package info (click to toggle)
opencv 4.10.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 282,092 kB
  • sloc: cpp: 1,178,079; xml: 682,621; python: 49,092; lisp: 31,150; java: 25,469; ansic: 11,039; javascript: 6,085; sh: 1,214; cs: 601; perl: 494; objc: 210; makefile: 173
file content (67 lines) | stat: -rw-r--r-- 1,719 bytes parent folder | download | duplicates (3)
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/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/dnn.hpp>

#include <iostream>
#include <cstdlib>

int main(int argc, char **argv)
{

    if (argc < 4)
    {
      std::cerr << "Usage " << argv[0] << ": "
                << "<model-definition-file> " << " "
                << "<model-weights-file> " << " "
                << "<test-image>\n";
      return -1;

    }
    cv::String model_prototxt = argv[1];
    cv::String model_binary = argv[2];
    cv::String test_image = argv[3];
    cv::dnn::Net net = cv::dnn::readNetFromCaffe(model_prototxt, model_binary);

    if (net.empty())
    {
        std::cerr << "Couldn't load the model !\n";
        return -2;
    }
    cv::Mat img = cv::imread(test_image);
    if (img.empty())
    {
        std::cerr << "Couldn't load image: " << test_image << "\n";
        return -3;
    }

    cv::Mat input_blob = cv::dnn::blobFromImage(
      img, 1.0, cv::Size(416, 416), cv::Scalar(104, 117, 123), false);

    cv::Mat prob;
    cv::TickMeter t;

    net.setInput(input_blob);
    t.start();
    prob = net.forward("predictions");
    t.stop();

    int prob_size[3] = {1000, 1, 1};
    cv::Mat prob_data(3, prob_size, CV_32F, prob.ptr<float>(0));

    double max_prob = -1.0;
    int class_idx = -1;
    for (int idx = 0; idx < prob.size[1]; ++idx)
    {
        double current_prob = prob_data.at<float>(idx, 0, 0);
        if (current_prob > max_prob)
        {
          max_prob = current_prob;
          class_idx = idx;
        }
    }
    std::cout << "Best class Index: " << class_idx << "\n";
    std::cout << "Time taken: " << t.getTimeSec() << "\n";
    std::cout << "Probability: " << max_prob * 100.0<< "\n";

    return 0;
}