OpenCV之VideoCapture的使用——打开网络摄像头/图像序列

来源:互联网 发布:淘宝卖家后台官网 编辑:程序博客网 时间:2024/06/05 00:20

OpenCV中的VideoCapture不仅可以打开视频、usb摄像头,还可以做很多事,例如读取流媒体文件,网络摄像头,图像序列等。OpenCV如何读取usb摄像头可以参考本人的另外一篇,地址如下:点击打开链接 。本文介绍如何读取网络摄像头、图像序列,并给出代码。


1、打开网络摄像头

(1)先保存URL;

(2)再使用VideoCapture的open方法:

bool VideoCapture::open(const string& filename)

    注: IP camera使用的是星网安防(Star-Net)的产品。


代码如下:

[cpp] view plain copy
 print?
  1. #include <opencv2/core/core.hpp>  
  2. #include <opencv2/highgui/highgui.hpp>  
  3. #include <iostream>  
  4.   
  5. int main(intchar**) {  
  6.     cv::VideoCapture vcap;  
  7.     cv::Mat image;  
  8.   
  9.     const std::string videoStreamAddress = "rtsp://192.168.1.156:554/ch1/1";   
  10.     /* it may be an address of an mjpeg stream,  
  11.     e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */  
  12.   
  13.     //open the video stream and make sure it's opened  
  14.     if(!vcap.open(videoStreamAddress)) {  
  15.         std::cout << "Error opening video stream or file" << std::endl;  
  16.         return -1;  
  17.     }  
  18.   
  19.     cv::namedWindow("Output Window");  
  20.   
  21.     for(;;) {  
  22.         if(!vcap.read(image)) {  
  23.             std::cout << "No frame" << std::endl;  
  24.             cv::waitKey();  
  25.         }  
  26.         cv::imshow("Output Window", image);  
  27.         if(cv::waitKey(1) >= 0) break;  
  28.     }     
  29. }  


2、打开图像序列

(1)保存图像序列的地址;

         图像序列要按照顺序命名,例如,b00001.bmp,b00002.bmp.,...。这样路径的最后使用b%05.bmp。

(2)使用VideoCapture的构造函数直接初始化序列。

VideoCapture::VideoCapture(const string& filename)


代码如下:

[cpp] view plain copy
 print?
  1. #include <opencv2/core/core.hpp>  
  2. #include <opencv2/highgui/highgui.hpp>  
  3.   
  4. #include <iostream>  
  5.   
  6. using namespace cv;  
  7. using namespace std;  
  8.   
  9. int main(int argc, char** argv)  
  10. {  
  11.     string first_file = "WavingTrees/b%05d.bmp";   
  12.     VideoCapture sequence(first_file);  
  13.   
  14.     if (!sequence.isOpened()){  
  15.         cerr << "Failed to open the image sequence!\n" << endl;  
  16.         return 1;  
  17.     }  
  18.   
  19.     Mat image;  
  20.     namedWindow("Image sequence", 1);  
  21.   
  22.     for(;;){  
  23.         sequence >> image;  
  24.   
  25.         if(image.empty()){  
  26.             cout << "End of Sequence" << endl;  
  27.             break;  
  28.         }  
  29.   
  30.         imshow("Image sequence", image);  
  31.         waitKey(0);  
  32.     }  
  33.   
  34.     return 0;  
  35. }  

本文转自:http://blog.csdn.net/tfygg/article/details/50404861
原创粉丝点击