上一篇通过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;
}
以上实现仅供参考。下一步尝试实现视频拼接的效果。