opencv2 加载RTSP视频流,内存溢出的问题

上一篇通过opencv2加载实时海康摄像头的视频流,视频可以加载成功,但是会发生错误,提示丢包或者解码错误。

如果打开资源管理器发现,并非解码时候发生错误 ,根本原因是电脑配置有问题,CPU资源耗尽,所以发生解码丢包等错误。

解决办法很简单,通过多线程的方式,把视频抽帧显示放到线程中处理,效果如下

 没有考虑线程安全的问题,简单实现代码如下

#include "stdafx.h"
#include "stdafx.h"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include <opencv2/video/video.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <xstring>
#include <thread>
using namespace std;
using namespace cv;

void ShowCam(std::string& url, const std::string& name)
{
	VideoCapture cap;
	cap.open(url);//呵呵,就这一句关键

	Mat Camera_CImg;
	Mat Camera_GImg;

	/*cap.set(CV_CAP_PROP_FRAME_HEIGHT, 640);
	cap.set(CV_CAP_PROP_FRAME_WIDTH, 800);*/

	if (!cap.isOpened())
		return ;

	std::thread t([](VideoCapture cap, std::string name){
		int iCount(0);
		while (true)
		{
			Mat frame, frame1, finalFrame;

			// Capture frame-by-frame
			cap >> frame;
			resize(frame, frame, Size(320, 240), 0, 0, INTER_CUBIC);

			// If the frame is empty, break immediately
			if (frame.empty()) {
				if (iCount++ < 10)
				{
					continue;
				}
				cout << "Frame is empty" << endl;
				break;
			}

			// Display the resulting frame
			imshow(name, frame);

			if (cvWaitKey(30) == 'q')
				break;
		}
	},cap, name);
	t.detach();
}

int _tmain(int argc, _TCHAR* argv[])
{
	std::string url("rtsp://admin:Admin12345@192.168.1.21:554/h264/ch1/sub/av_stream");
	ShowCam(url, "first_cam");
	std::string url2("rtsp://admin:xy123456@192.168.1.152:554/h264/ch1/sub/av_stream");
	ShowCam(url2, "second_cam");

	getchar();
	return 0;
}

以上实现仅供参考。下一步尝试实现视频拼接的效果。 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老朱自强不息

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值