Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/cpp/detection/detect_vid/detect_vid.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// capture the video26VideoCapture cap("../../../input/video_1.mp4");27// get the video frames' width and height for proper saving of videos28int frame_width = static_cast<int>(cap.get(3));29int frame_height = static_cast<int>(cap.get(4));30// create the `VideoWriter()` object31VideoWriter out("../../../outputs/video_result.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 30,32Size(frame_width, frame_height));3334while (cap.isOpened()) {35Mat image;36bool isSuccess = cap.read(image);3738if (! isSucess) break;3940int image_height = image.cols;41int image_width = image.rows;42//create blob from image43Mat blob = blobFromImage(image, 1.0, Size(300, 300), Scalar(127.5, 127.5, 127.5),44true, false);45//create blob from image46model.setInput(blob);47//forward pass through the model to carry out the detection48Mat output = model.forward();4950Mat detectionMat(output.size[2], output.size[3], CV_32F, output.ptr<float>());5152for (int i = 0; i < detectionMat.rows; i++){53int class_id = detectionMat.at<float>(i, 1);54float confidence = detectionMat.at<float>(i, 2);5556// Check if the detection is of good quality57if (confidence > 0.4){58int box_x = static_cast<int>(detectionMat.at<float>(i, 3) * image.cols);59int box_y = static_cast<int>(detectionMat.at<float>(i, 4) * image.rows);60int box_width = static_cast<int>(detectionMat.at<float>(i, 5) * image.cols - box_x);61int box_height = static_cast<int>(detectionMat.at<float>(i, 6) * image.rows - box_y);62rectangle(image, Point(box_x, box_y), Point(box_x+box_width, box_y+box_height), Scalar(255,255,255), 2);63putText(image, class_names[class_id-1].c_str(), Point(box_x, box_y-5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0,255,255), 1);64}65}6667imshow("image", image);68out.write(image);69int k = waitKey(10);70if (k == 113){71break;72}73}7475cap.release();76destroyAllWindows();77}787980