OpenCV中的VideoCapture不仅可以打开视频、usb摄像头,还可以做很多事,例如读取流媒体文件,网络摄像头,图像序列等。OpenCV如何读取usb摄像头可以参考本人的另外一篇,地址如下:点击打开链接 。本文介绍如何读取网络摄像头、图像序列,并给出代码。
1、打开网络摄像头
(1)先保存URL;
(2)再使用VideoCapture的open方法:
bool VideoCapture::open(const string& filename)
注: IP camera使用的是星网安防(Star-Net)的产品。
代码如下:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://192.168.1.156:554/ch1/1";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
2、打开图像序列
(1)保存图像序列的地址;
图像序列要按照顺序命名,例如,b00001.bmp,b00002.bmp.,...。这样路径的最后使用b%05.bmp。
(2)使用VideoCapture的构造函数直接初始化序列。
VideoCapture:: VideoCapture ( const string& filename )
代码如下:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
string first_file = "WavingTrees/b%05d.bmp";
VideoCapture sequence(first_file);
if (!sequence.isOpened()){
cerr << "Failed to open the image sequence!\n" << endl;
return 1;
}
Mat image;
namedWindow("Image sequence", 1);
for(;;){
sequence >> image;
if(image.empty()){
cout << "End of Sequence" << endl;
break;
}
imshow("Image sequence", image);
waitKey(0);
}
return 0;
}
3、个人觉得使用下面两个方法都可以打开网络摄像头以及图像序列。有兴趣的,可以修改上述代码,可行的话,麻烦请告知。
bool VideoCapture::open(const string& filename)
VideoCapture::VideoCapture(const string& filename)