Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/cpp/detection/detect_img/detect_img.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
12
int main(int, char**) {
13
std::vector<std::string> class_names;
14
ifstream ifs(string("../../../input/object_detection_classes_coco.txt").c_str());
15
string line;
16
while (getline(ifs, line))
17
{
18
class_names.push_back(line);
19
}
20
21
// load the neural network model
22
auto model = readNet("../../../input/frozen_inference_graph.pb",
23
"../../../input/ssd_mobilenet_v2_coco_2018_03_29.pbtxt.txt",
24
"TensorFlow");
25
26
// read the image from disk
27
Mat image = imread("../../../input/image_2.jpg");
28
int image_height = image.cols;
29
int image_width = image.rows;
30
//create blob from image
31
Mat blob = blobFromImage(image, 1.0, Size(300, 300), Scalar(127.5, 127.5, 127.5),
32
true, false);
33
//create blob from image
34
model.setInput(blob);
35
//forward pass through the model to carry out the detection
36
Mat output = model.forward();
37
38
Mat detectionMat(output.size[2], output.size[3], CV_32F, output.ptr<float>());
39
40
for (int i = 0; i < detectionMat.rows; i++){
41
int class_id = detectionMat.at<float>(i, 1);
42
float confidence = detectionMat.at<float>(i, 2);
43
44
// Check if the detection is of good quality
45
if (confidence > 0.4){
46
int box_x = static_cast<int>(detectionMat.at<float>(i, 3) * image.cols);
47
int box_y = static_cast<int>(detectionMat.at<float>(i, 4) * image.rows);
48
int box_width = static_cast<int>(detectionMat.at<float>(i, 5) * image.cols - box_x);
49
int box_height = static_cast<int>(detectionMat.at<float>(i, 6) * image.rows - box_y);
50
rectangle(image, Point(box_x, box_y), Point(box_x+box_width, box_y+box_height), Scalar(255,255,255), 2);
51
putText(image, class_names[class_id-1].c_str(), Point(box_x, box_y-5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0,255,255), 1);
52
}
53
}
54
55
imshow("image", image);
56
imwrite("../../../outputs/image_result.jpg", image);
57
waitKey(0);
58
destroyAllWindows();
59
60
}
61
62