1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main() { // Open video file VideoCapture cap("path/to/your/video.mp4"); if (!cap.isOpened()) { cerr << "Error: Could not open video file!" << endl; return -1; } namedWindow("Video Stream", WINDOW_AUTOSIZE); while (true) { Mat frame; cap >> frame; // Capture a new frame from the video if (frame.empty()) { break; // Exit loop if there are no more frames } imshow("Video Stream", frame); // Display the current frame // Exit video stream if 'q' is pressed if (waitKey(30) == 'q') { break; } } cap.release(); // Release video file destroyAllWindows(); // Close all OpenCV windows return 0; } |
Explanation
- Include Libraries:
#include <opencv2/opencv.hpp>
includes the OpenCV library for video processing.#include <iostream>
is used for input and output operations.
Advertisement - Open Video File:
VideoCapture cap("path/to/your/video.mp4");
opens the video file for reading.- Checks if the file was opened successfully. If not, prints an error message and exits.
Advertisement - Create Window:
namedWindow("Video Stream", WINDOW_AUTOSIZE);
creates a window to display the video frames.
- Video Streaming Loop:
cap >> frame;
captures the next frame from the video.- Checks if the frame is empty (end of video). If so, exits the loop.
imshow("Video Stream", frame);
displays the current frame in the created window.waitKey(30);
waits for 30 milliseconds for a key press. If the ‘q’ key is pressed, exits the loop.
Advertisement - Cleanup:
cap.release();
releases the video file resource.destroyAllWindows();
closes all OpenCV windows.