Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/cpp/classify/classify.cpp
3150 views
1
#include <iostream>
2
#include <fstream>
3
#include <opencv2/opencv.hpp>
4
#include <opencv2/dnn.hpp>
5
#include <opencv2/dnn/all_layers.hpp>
6
7
using namespace std;
8
using namespace cv;
9
using namespace dnn;
10
11
int main(int, char**) {
12
std::vector<std::string> class_names;
13
ifstream ifs(string("../../input/classification_classes_ILSVRC2012.txt").c_str());
14
string line;
15
while (getline(ifs, line))
16
{
17
class_names.push_back(line);
18
}
19
20
// load the neural network model
21
auto model = readNet("../../input/DenseNet_121.prototxt",
22
"../../input/DenseNet_121.caffemodel",
23
"Caffe");
24
25
// load the image from disk
26
Mat image = imread("../../input/image_1.jpg");
27
// create blob from image
28
Mat blob = blobFromImage(image, 0.01, Size(224, 224), Scalar(104, 117, 123));
29
30
// set the input blob for the neural network
31
model.setInput(blob);
32
// forward pass the image blob through the model
33
Mat outputs = model.forward();
34
35
Point classIdPoint;
36
double final_prob;
37
minMaxLoc(outputs.reshape(1, 1), 0, &final_prob, 0, &classIdPoint);
38
int label_id = classIdPoint.x;
39
40
// Print predicted class.
41
string out_text = format("%s, %.3f", (class_names[label_id].c_str()), final_prob);
42
// put the class name text on top of the image
43
putText(image, out_text, Point(25, 50), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 255, 0),
44
2);
45
46
imshow("Image", image);
47
imwrite("../../outputs/result_image.jpg", image);
48
}
49
50