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 39 40 41 42 43 |
#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 Player", WINDOW_AUTOSIZE); bool isPaused = false; while (true) { Mat frame; if (!isPaused) { cap >> frame; // Capture a new frame from the video if (frame.empty()) { break; // Exit loop if there are no more frames } } imshow("Video Player", frame); // Display the current frame int key = waitKey(30); // Wait for 30 ms for a key press if (key == 'q') { break; // Exit video player if 'q' is pressed } else if (key == 'p') { isPaused = !isPaused; // Toggle pause/resume if 'p' is pressed } } cap.release(); // Release video file destroyAllWindows(); // Close all OpenCV windows return 0; } |
Explanation
- Include Libraries:
#include <opencv2/opencv.hpp>
: Includes OpenCV for video processing.#include <iostream>
: Used for input and output operations.
- 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.
- Create Window:
namedWindow("Video Player", WINDOW_AUTOSIZE);
: Creates a window to display the video frames.
- Playback Control:
bool isPaused = false;
: Initializes a flag to control playback state.- Inside the loop:
- If
isPaused
isfalse
, capture a new frame from the video. - If
frame.empty()
, it means the video has ended, and the loop is exited. imshow("Video Player", frame);
displays the current frame in the window.waitKey(30);
waits for 30 milliseconds for a key press. If ‘q’ is pressed, the loop exits. If ‘p’ is pressed, it toggles theisPaused
state to pause or resume playback.
- If
- Cleanup:
cap.release();
: Releases the video file resource.destroyAllWindows();
: Closes all OpenCV windows.