簡體   English   中英

OpenCV如何有效地編碼和發送網絡攝像頭視頻流的數據?

[英]OpenCV how to encode and send data of webcam video stream efficiently?

我有這個OpenCV C ++代碼,它從凸輪上獲取圖像,對其進行編碼並將其發送到STDOUT。

#include <unistd.h> //STDOUT_FILENO
#include "opencv2/opencv.hpp"
#include <iostream>
#include <fcntl.h>
using namespace std;
using namespace cv;

#define BUFLEN 4096

int main(int argc, char *argv[])
{
    Mat frame;
    std::vector<uchar> buf;

    int bak, temp;

    //read image as grayscale
    namedWindow( "Camera", WINDOW_AUTOSIZE );
    //redirect stdout to NULL in order to avoid printing to STDOUT undesired stuff
    fflush(stdout);
    bak = dup(1);
    temp = open("/dev/null", O_WRONLY);
    dup2(temp, 1);
    close(temp  );
    VideoCapture cam(0 + CAP_V4L);
    cam>>frame;
    sleep(1);
    if (!cam.isOpened())
    {
        cout << "\nCould not open reference " << 0 << endl;
        return -1;
    }
    for (int i=0; i<5; i++)
    {
        cam>>frame;
    }
    /*Set the normal STDOUT back*/
    fflush(stdout);
    dup2(bak, 1);
    close(bak);

    //encode image and put data into the vector buf
    imencode(".png",frame, buf);
    //send the total size of vector to parent
    cout<<buf.size()<<endl;
    unsigned int written= 0;

    int i = 0;
    size_t toWrite = 0;
    //send until all bytes have been sent
    FILE * f = fdopen(STDOUT_FILENO, "w");
    while (written<buf.size())
    {
        //send the current block of data
        toWrite = BUFLEN < (buf.size()-written) ? BUFLEN : (buf.size()-written);
        //written += write(STDOUT_FILENO, buf.data()+written, toWrite);
        written += toWrite*fwrite ( buf.data()+written, toWrite, 1, f );
        i++;
    }
    return 0;
}

現在,而不是圖像,我想從凸輪拍攝無限連續視頻。 一種解決方案是在任何給定的秒內采用幀,對幀進行編碼並將其傳輸(將其打印到STDOUT),所有動作都在無限循環內。

是否有更好的解決方案,比編碼更有效,並在每次迭代時發送每個幀?

基本上,視頻流是預定義順序的幀序列。

您可以簡單地將幀作為圖像一個接一個地發送。 這沒有什么根本性的錯誤,但不一定是最優的(這也取決於你對最優的定義)。

在通信中,其中一個方面是最小化傳輸的數據量。 只需將幀作為圖像發送即可進行一些壓縮(例如jpeg)。 用於視頻的更好的壓縮算法(例如mpeg)使用序列的時間屬性。 如果存在(大多數)靜態幀,則可以限制自己發送有關更改部分的數據並假設背景相同。 這與通信兩端的一些處理有關,但可能會提高通信速度(假設鏈路是瓶頸)。 這也會給系統增加很多復雜性,因此首先考慮潛在的優勢(找出瓶頸)。

我不確定您的應用程序的用途,但將視頻流發送到stdout可能不一定是最好的主意。 考慮使用管道或套接字(后者允許您很容易通過網絡傳輸數據,這可能是一個很好的結果)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM