【OpenCV 】 网络摄像头

 1  RTSP

  RTSP (Real Time Streaming Protocol),是一种语法和操作类似 HTTP 协议,专门用于音频和视频的应用层协议。 和 HTTP 类似,RTSP 也使用 URL 地址。

  海康网络摄像头的 RTSP URL 格式如下:

复制代码

rtsp://[username]:[password]@[ip]:[port]/[codec]/[channel]/[subtype]/av_stream
1) username  用户名,常用 admin
2) password  密码,常用 12345
3) ip        摄像头IP,如 192.0.0.64
4) port      端口号,默认为 554
5) codec     视频编码模式,有 h264、MPEG-4、mpeg4 等
6) channel   通道号,起始为1,例如通道1,则为 ch1
7) subtype   码流类型,主码流为 main,辅码流为 sub

复制代码

  大华网络摄像头的 RTSP URL 格式如下:

rtsp://[username]:[password]@[ip]:[port]/cam/realmonitor?[channel=1]&[subtype=1] 
1) username、password、ip、port 同上
2) channel  通道号,起始为1,例如通道2,则为 channel=2
3) subtype  码流类型,主码流为0(即 subtype=0),辅码流为1(即 subtype=1)

 

2  VideoCapture 类

  VideoCapture 类是 OpenCV 中用来操作视频流的类,可以在构造函数中打开视频,其参数支持以下三种类型:

  1)  name of video file (eg. `video.avi`)

  2)  image sequence (eg. `img_%02d.jpg`, which will read samples like `img_00.jpg, img_01.jpg, img_02.jpg, ...`)

  3)  URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`).

// Open video file or a capturing device or a IP video stream for video capturing
// VideoCapture 构造函数
CV_WRAP VideoCapture(const String& filename);

  也可以构造后,再使用 open 函数来打开

// 参数同 VideoCapture 的构造函数
CV_WRAP virtual bool open(const String& filename);

 

3  代码

  下面是以海康威视的某款网络摄像头为例,使用 OpenCV 的 VideoCapture 类来显示实时视频

复制代码

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;

int main(int argc, char** argv)
{
    String rtsp_addr = "rtsp://admin:[email protected]:554/MPEG-4/ch1/main/av_stream";

    VideoCapture cap(rtsp_addr);
//    cap.open(rtsp_addr);

    Mat frame;

    for(;;) {
        cap >> frame;
        if(frame.empty())
            break;

        imshow("Video Stream", frame);

        if (waitKey(10) == 'q')
            break;
    }
}

复制代码

  附上一张园区的部分视频截图如下:

  

 

参考资料:

  Multimedia Over IP: RSVP, RTP, RTCP, RTSP

  海康、大华IpCamera RTSP地址和格式    xiejiashu

 <Learning OpenCV3>  chapter 8