模仿视频抓帧实现

路口或某些场所可能并不会把从摄像头获取到的视频全部存储下来或对所有的视频帧进行处理,即摄像设备是一直处于打开状态,可能会根据需要间隔性的抓取其中一帧,或当某事件触发时才会抓取当前的一帧数据进行处理。这里使用两个线程来模仿此场景。主线程用于开启视频设备,另一个线程在间隔指定时间后抓取当前帧并保存。code较简单,没有使用队列和线程锁。

测试代码如下:

#include <string>
#include <fstream>
#include <vector>
#include <cmath>
#include <chrono>
#include <thread>

#include <opencv2/opencv.hpp>

namespace {

volatile bool grab_video_frame = false;
volatile bool running = true;
cv::Mat frame;

void save_video_frame()
{
#ifdef _MSC_VER
	std::string path = "E:/GitCode/OpenCV_Test/test_images/";
#else
	std::string path = "test_images/";
#endif
	for (int i = 0; i < 5; ++i) {
		grab_video_frame = true;
		auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
		std::string name = path + std::to_string(now) + ".png";
		fprintf(stdout, "start to grab frame: index: %d, name: %s\n", i + 1, name.c_str());

		while (1) {
			if (!grab_video_frame) {
				cv::imwrite(name, frame);
				break;
			}
		}

		std::this_thread::sleep_for(std::chrono::seconds(5)); // 5 seconds grab a frame
	}

	running = false;
}

} // namespace

int test_opencv_grab_video_frame()
{
	cv::VideoCapture cap(0);
	if (!cap.isOpened()) {
		fprintf(stderr, "fail to open capture\n");
		return -1;
	}

	std::thread th(save_video_frame);

	while (running) {
		if (grab_video_frame) {
			cap >> frame; // instead of queue
			grab_video_frame = false; // instead of thread lock
		}
	}

	th.join();

	return 0;
}

执行结果如下:

GitHubhttps://github.com/fengbingchun/OpenCV_Test

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值