opencv读取视频的特定帧或每秒截取指定数量的图片

假如视频的帧率是30,时长50秒,则直接每一帧都保存一共会保存1500张图,这显然太多了。因此考虑如何每秒只截取一帧并进行处理。

代码如下:

#include <iostream>
#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <fstream>
#define SAVEPATH "C:/Users/z/Desktop/img_files/"
using namespace std;
using namespace cv;
int main()
{
 string file = "C:/Users/z/Desktop/IMG_4380.mp4";
 VideoCapture cap(file);
 if (!cap.isOpened())
 {
 cout << "open video file failed." << endl;
 }
 int frame_cnt = 0;
 int num = 0;
 Mat img;
 
 while (true)
 {
 bool success = cap.read(img);
 if (!success)
 {
 cout<< "Process " << num << " frames from" << file << endl;
 break;
 }
 if (img.empty())
 {
 cout << "frame capture failed." << endl;
 break;
 }
 
 if (frame_cnt % 30 == 0)
 {
 ++num;
 string name = SAVEPATH + to_string(num) + ".jpg";
 imwrite(name, img);
 cout << "processed " << num << " frames.\n" << endl;
 }
 ++frame_cnt;
 }
 
 cout << cap.get(CV_CAP_PROP_FRAME_COUNT) << endl;
 cout << cap.get(CV_CAP_PROP_FPS) << endl;
 cap.release();
 return 0;

}

精华就在if (frame_cnt % 30 == 0)这一句。

此外,在while循环中加入waitKey(1000)做延时并不会起作用,因为至少有一次用到imgshow函数时waitKey才会起作用。
 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值