videocapture_camera.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <opencv2/core.hpp>
  2. #include <opencv2/videoio.hpp>
  3. #include <opencv2/highgui.hpp>
  4. #include <opencv2/imgproc.hpp> // cv::Canny()
  5. #include <iostream>
  6. using namespace cv;
  7. using std::cout; using std::cerr; using std::endl;
  8. int main(int, char**)
  9. {
  10. Mat frame;
  11. cout << "Opening camera..." << endl;
  12. VideoCapture capture(0); // open the first camera
  13. if (!capture.isOpened())
  14. {
  15. cerr << "ERROR: Can't initialize camera capture" << endl;
  16. return 1;
  17. }
  18. cout << "Frame width: " << capture.get(CAP_PROP_FRAME_WIDTH) << endl;
  19. cout << " height: " << capture.get(CAP_PROP_FRAME_HEIGHT) << endl;
  20. cout << "Capturing FPS: " << capture.get(CAP_PROP_FPS) << endl;
  21. cout << endl << "Press 'ESC' to quit, 'space' to toggle frame processing" << endl;
  22. cout << endl << "Start grabbing..." << endl;
  23. size_t nFrames = 0;
  24. bool enableProcessing = false;
  25. int64 t0 = cv::getTickCount();
  26. int64 processingTime = 0;
  27. for (;;)
  28. {
  29. capture >> frame; // read the next frame from camera
  30. if (frame.empty())
  31. {
  32. cerr << "ERROR: Can't grab camera frame." << endl;
  33. break;
  34. }
  35. nFrames++;
  36. if (nFrames % 10 == 0)
  37. {
  38. const int N = 10;
  39. int64 t1 = cv::getTickCount();
  40. cout << "Frames captured: " << cv::format("%5lld", (long long int)nFrames)
  41. << " Average FPS: " << cv::format("%9.1f", (double)getTickFrequency() * N / (t1 - t0))
  42. << " Average time per frame: " << cv::format("%9.2f ms", (double)(t1 - t0) * 1000.0f / (N * getTickFrequency()))
  43. << " Average processing time: " << cv::format("%9.2f ms", (double)(processingTime) * 1000.0f / (N * getTickFrequency()))
  44. << std::endl;
  45. t0 = t1;
  46. processingTime = 0;
  47. }
  48. if (!enableProcessing)
  49. {
  50. imshow("Frame", frame);
  51. }
  52. else
  53. {
  54. int64 tp0 = cv::getTickCount();
  55. Mat processed;
  56. cv::Canny(frame, processed, 400, 1000, 5);
  57. processingTime += cv::getTickCount() - tp0;
  58. imshow("Frame", processed);
  59. }
  60. int key = waitKey(1);
  61. if (key == 27/*ESC*/)
  62. break;
  63. if (key == 32/*SPACE*/)
  64. {
  65. enableProcessing = !enableProcessing;
  66. cout << "Enable frame processing ('space' key): " << enableProcessing << endl;
  67. }
  68. }
  69. std::cout << "Number of captured frames: " << nFrames << endl;
  70. return nFrames > 0 ? 0 : 1;
  71. }