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_vid/detect_vid.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
// capture the video
27
VideoCapture cap("../../../input/video_1.mp4");
28
// get the video frames' width and height for proper saving of videos
29
int frame_width = static_cast<int>(cap.get(3));
30
int frame_height = static_cast<int>(cap.get(4));
31
// create the `VideoWriter()` object
32
VideoWriter out("../../../outputs/video_result.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 30,
33
Size(frame_width, frame_height));
34
35
while (cap.isOpened()) {
36
Mat image;
37
bool isSuccess = cap.read(image);
38
39
if (! isSucess) break;
40
41
int image_height = image.cols;
42
int image_width = image.rows;
43
//create blob from image
44
Mat blob = blobFromImage(image, 1.0, Size(300, 300), Scalar(127.5, 127.5, 127.5),
45
true, false);
46
//create blob from image
47
model.setInput(blob);
48
//forward pass through the model to carry out the detection
49
Mat output = model.forward();
50
51
Mat detectionMat(output.size[2], output.size[3], CV_32F, output.ptr<float>());
52
53
for (int i = 0; i < detectionMat.rows; i++){
54
int class_id = detectionMat.at<float>(i, 1);
55
float confidence = detectionMat.at<float>(i, 2);
56
57
// Check if the detection is of good quality
58
if (confidence > 0.4){
59
int box_x = static_cast<int>(detectionMat.at<float>(i, 3) * image.cols);
60
int box_y = static_cast<int>(detectionMat.at<float>(i, 4) * image.rows);
61
int box_width = static_cast<int>(detectionMat.at<float>(i, 5) * image.cols - box_x);
62
int box_height = static_cast<int>(detectionMat.at<float>(i, 6) * image.rows - box_y);
63
rectangle(image, Point(box_x, box_y), Point(box_x+box_width, box_y+box_height), Scalar(255,255,255), 2);
64
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);
65
}
66
}
67
68
imshow("image", image);
69
out.write(image);
70
int k = waitKey(10);
71
if (k == 113){
72
break;
73
}
74
}
75
76
cap.release();
77
destroyAllWindows();
78
}
79
80