Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/cpp/detection/detect_img/detect_img.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;91011int main(int, char**) {12std::vector<std::string> class_names;13ifstream ifs(string("../../../input/object_detection_classes_coco.txt").c_str());14string line;15while (getline(ifs, line))16{17class_names.push_back(line);18}1920// load the neural network model21auto model = readNet("../../../input/frozen_inference_graph.pb",22"../../../input/ssd_mobilenet_v2_coco_2018_03_29.pbtxt.txt",23"TensorFlow");2425// read the image from disk26Mat image = imread("../../../input/image_2.jpg");27int image_height = image.cols;28int image_width = image.rows;29//create blob from image30Mat blob = blobFromImage(image, 1.0, Size(300, 300), Scalar(127.5, 127.5, 127.5),31true, false);32//create blob from image33model.setInput(blob);34//forward pass through the model to carry out the detection35Mat output = model.forward();3637Mat detectionMat(output.size[2], output.size[3], CV_32F, output.ptr<float>());3839for (int i = 0; i < detectionMat.rows; i++){40int class_id = detectionMat.at<float>(i, 1);41float confidence = detectionMat.at<float>(i, 2);4243// Check if the detection is of good quality44if (confidence > 0.4){45int box_x = static_cast<int>(detectionMat.at<float>(i, 3) * image.cols);46int box_y = static_cast<int>(detectionMat.at<float>(i, 4) * image.rows);47int box_width = static_cast<int>(detectionMat.at<float>(i, 5) * image.cols - box_x);48int box_height = static_cast<int>(detectionMat.at<float>(i, 6) * image.rows - box_y);49rectangle(image, Point(box_x, box_y), Point(box_x+box_width, box_y+box_height), Scalar(255,255,255), 2);50putText(image, class_names[class_id-1].c_str(), Point(box_x, box_y-5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0,255,255), 1);51}52}5354imshow("image", image);55imwrite("../../../outputs/image_result.jpg", image);56waitKey(0);57destroyAllWindows();5859}606162