使用OpenCV進行網絡攝像頭的圖像采集及視頻存儲


rtspURL格式

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

主要參考了這篇博客中的內容。
ip地址可以通過SADPTOOL獲取,端口號注意是填rtsp端口號,可在瀏覽器輸入ip地址進入配置中查詢。

視頻保存

使用了VideoWriter類(注:windows系統中保存文件路徑不填寫絕對路徑可能會出問題,原因未知)。用鼠標響應函數和滑動調函數模擬了開關,點擊滑動條開始錄制,再次點擊停止錄制。

代碼

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;



int writeFlag = 0;
void OnMouseClick(int event, int x, int y, int flag, void* param /* = NULL */)
{
    if(event==CV_EVENT_LBUTTONDOWN)
      writeFlag = !writeFlag;
}

int main(int argc, char** argv)
{
    
    String rtsp_addr = "rtsp://admin:123456@192.168.1.1:554/MPEG-4/ch1/main/av_stream ";
    namedWindow("Video Stream", CV_WINDOW_AUTOSIZE);
    createTrackbar("writeFlag:\n", "Video Stream", &writeFlag, 1);
    setMouseCallback("Video Stream", OnMouseClick);
    
    VideoCapture cap(rtsp_addr);
    
    Mat frame;
    Mat BackGround;
    cap >> BackGround;
    
    VideoWriter writer("F:/opencv3/test2/x64/Debug/VideoTest.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25.0, Size(1280, 720));
    for (;;) {
        cap >> frame;
        if (frame.empty())
            break;
        
        if(writeFlag)
            writer << frame;
        imshow("Video Stream", frame);
        
        if (waitKey(10) == 'q')
            break;
    }
    //waitKey(0);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM