Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/cpp/classify/classify.cpp
3150 views
#include <iostream>1#include <fstream>2#include <opencv2/opencv.hpp>3#include <opencv2/dnn.hpp>4#include <opencv2/dnn/all_layers.hpp>56using namespace std;7using namespace cv;8using namespace dnn;910int main(int, char**) {11std::vector<std::string> class_names;12ifstream ifs(string("../../input/classification_classes_ILSVRC2012.txt").c_str());13string line;14while (getline(ifs, line))15{16class_names.push_back(line);17}1819// load the neural network model20auto model = readNet("../../input/DenseNet_121.prototxt",21"../../input/DenseNet_121.caffemodel",22"Caffe");2324// load the image from disk25Mat image = imread("../../input/image_1.jpg");26// create blob from image27Mat blob = blobFromImage(image, 0.01, Size(224, 224), Scalar(104, 117, 123));2829// set the input blob for the neural network30model.setInput(blob);31// forward pass the image blob through the model32Mat outputs = model.forward();3334Point classIdPoint;35double final_prob;36minMaxLoc(outputs.reshape(1, 1), 0, &final_prob, 0, &classIdPoint);37int label_id = classIdPoint.x;3839// Print predicted class.40string out_text = format("%s, %.3f", (class_names[label_id].c_str()), final_prob);41// put the class name text on top of the image42putText(image, out_text, Point(25, 50), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 255, 0),432);4445imshow("Image", image);46imwrite("../../outputs/result_image.jpg", image);47}484950