当前位置:   article > 正文

OpenCV 实时目标检测_opencv 实时调用detect

opencv 实时调用detect

0.概述

1.原理介绍

2.代码实现

  1. #include <iostream>
  2. #include <opencv2/opencv.hpp>
  3. int main() {
  4. // Load pre-trained MobileNet SSD model and configuration
  5. std::string model = "path_to_mobilenet_iter_73000.caffemodel";
  6. std::string config = "path_to_deploy.prototxt";
  7. cv::dnn::Net net = cv::dnn::readNetFromCaffe(config, model);
  8. // Use webcam for real-time detection
  9. cv::VideoCapture cap(0);
  10. if (!cap.isOpened()) {
  11. std::cerr << "Error: Couldn't open the webcam." << std::endl;
  12. return -1;
  13. }
  14. while (true) {
  15. cv::Mat frame;
  16. cap >> frame;
  17. // Prepare the frame for the neural network
  18. cv::Mat blob = cv::dnn::blobFromImage(frame, 0.007843, cv::Size(300, 300), 127.5);
  19. net.setInput(blob);
  20. // Forward pass
  21. cv::Mat detection = net.forward();
  22. // Process the detection
  23. for (int i = 0; i < detection.size[2]; i++) {
  24. float confidence = detection.at<float>(0, 0, i, 2);
  25. if (confidence > 0.2) { // Threshold for confidence
  26. int classId = static_cast<int>(detection.at<float>(0, 0, i, 1));
  27. int left = static_cast<int>(detection.at<float>(0, 0, i, 3) * frame.cols);
  28. int top = static_cast<int>(detection.at<float>(0, 0, i, 4) * frame.rows);
  29. int right = static_cast<int>(detection.at<float>(0, 0, i, 5) * frame.cols);
  30. int bottom = static_cast<int>(detection.at<float>(0, 0, i, 6) * frame.rows);
  31. // Draw bounding box for detected object
  32. cv::rectangle(frame, cv::Point(left, top), cv::Point(right, bottom), cv::Scalar(0, 255, 0), 2);
  33. }
  34. }
  35. // Display the frame with detections
  36. cv::imshow("Real-time Object Detection", frame);
  37. // Exit on pressing 'q'
  38. if (cv::waitKey(1) == 'q') break;
  39. }
  40. cap.release();
  41. cv::destroyAllWindows();
  42. return 0;
  43. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/794073
推荐阅读
相关标签
  

闽ICP备14008679号