用c++编写一段程序,利用opencv来读取视频
时间: 2024-03-08 19:46:19 浏览: 27
好的,以下是一段用C++和OpenCV读取视频的示例代码:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// 打开视频文件
VideoCapture cap("test.mp4");
// 检查是否成功打开视频文件
if (!cap.isOpened())
{
cerr << "Failed to open the video file!" << endl;
return -1;
}
// 获取视频文件的帧数和帧率
int frameCount = cap.get(CAP_PROP_FRAME_COUNT);
double fps = cap.get(CAP_PROP_FPS);
// 输出视频文件信息
cout << "Video has " << frameCount << " frames with " << fps << " fps." << endl;
// 循环读取视频帧
while (true)
{
Mat frame;
bool success = cap.read(frame);
// 检查是否成功读取视频帧
if (!success)
{
cerr << "Failed to read a frame from the video stream!" << endl;
break;
}
// 在窗口中显示视频帧
imshow("Video Frame", frame);
// 等待一段时间,按下ESC键退出循环
if (waitKey(1000 / fps) == 27)
{
cout << "ESC key is pressed by the user. Stopping the video..." << endl;
break;
}
}
// 释放资源
cap.release();
destroyAllWindows();
return 0;
}
```
这段代码利用VideoCapture类打开一个名为test.mp4的视频文件,并循环读取每一帧视频,然后在一个名为"Video Frame"的窗口中显示它们。按下ESC键会退出循环并关闭窗口。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)