项目需要,最近在研究网络摄像头视频流的接收。之前用的vlc,操作简单,接收效果特别好,略有延迟,而且vlc是开源的!!!如果代码能力有点强悍,可以自己改写。
可是呢,可是呢,这又会是个比较大的工程对不对,懒人有懒人的办法,利用opencv自带函数接收rtsp视频流的功能,opencv2和opencv3代码都在这里,以下:
Opencv2:
#include "opencv2/opencv.hpp"
#include"opencv2/core/core.hpp"
#include<opencv2/video/video.hpp>
#include"opencv2/highgui/highgui.hpp"
#include<fstream>
#include<iostream>
//作者的opencv版本3.0,所以代码是2.x版本,包含的包是3.0的包
using namespace cv;
using namespace std;
int main(int argc, char **argv){
IplImage *pFrame = NULL, *srcImage=NULL;
CvCapture *pCapture = NULL;
pCapture =cvCreateFileCapture("rtsp://0.0.0.1/stream1");//your own rtsp address
if(!pCapture){
printf("Can not get the videostream from the camera!\n");
return NULL;
}
doublerate=cvGetCaptureProperty(pCapture,CV_CAP_PROP_FPS);
CvSize size=cvSize((int)cvGetCaptureProperty(pCapture,CV_CAP_PROP_FRAME_WIDTH),(int)cvGetCaptureProperty(pCapture,CV_CAP_PROP_FRAME_HEIGHT));
CvVideoWriter*writer=cvCreateVideoWriter("videotest.avi",CV_FOURCC('M','J','P','G'),rate,size);
while(1){
pFrame = cvQueryFrame(pCapture);
srcImage=cvCloneImage(pFrame);
cvWriteFrame(writer,srcImage);
cvShowImage("123234",srcImage);
//cout<<pFrame->width<<","<<pFrame->height<<endl;
cvWaitKey(30);
cvReleaseImage(&srcImage);
srcImage=NULL;
}
cvReleaseCapture(&pCapture);
cvReleaseImage(&pFrame);
return 0;
}
Opencv3:
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapturecap;
cap.open("rtsp://0.0.0.1/stream1");//呵呵,就这一句关键
MatCamera_CImg;
MatCamera_GImg;
cap.set(CV_CAP_PROP_FRAME_HEIGHT,768);
cap.set(CV_CAP_PROP_FRAME_WIDTH,1024);
if (!cap.isOpened())
return 1024;
while (1)
{
cap>> Camera_CImg;
if(Camera_CImg.empty())
break;
cvtColor(Camera_CImg,Camera_GImg, CV_RGB2GRAY);
imshow("input", Camera_CImg);
if (cvWaitKey(10) == 'q')
break;
}
system("pause");
return 0;
}