Search code examples
opencvboostwebcamlive-streaming

Introducing delay in live stream using opencv boost


I am trying to create a delay in live stream obtained from webcam. I am using opencv. However, i am unable to generate the desired delay. I am confused how to set and handle FPS and delay. below is my code: I am using a constant value for fps at the moment. But i am not sure if we can do that. Currently, the stream is shown with some initial delay while the queue is being filled. but after that, there is no delay in the stream.

fps=15;
wait= (1000.0/fps);
queue<cv::Mat> _buffer;
while(1)
{
    int size_x=0;
    //grad a frame from the video camers

    boost::unique_lock<boost::mutex> lock(mutex, boost::defer_lock);
    bool read = cap.read(image);
    if(!read)
        break;

    locked= lock.try_lock();

    if(locked){
        if(image.data){
            _buffer.push(image);
            waitKey(wait);
            if((int)_buffer.size() > (buffer_lenght))
            {
                popped_img=_buffer.front();
                _buffer.pop();
               imshow("VideoCaptureTutorial", popped_img);
            }
        }
        lock.unlock();
    }

Solution

  • I found two problems in your code.

    1) Try decreasing waitKey value, with that long waiting period, opencv might skip frames when its a live stream. Which isn't related to your question, but, I think it might be helpful.

    waitKey(30);
    

    the above line might be good enough.

    2) you have to push Mat.clone(), I assume, this might solve your problem in this case.

     _buffer.push(image.clone());
    

    Opencv's get/set fps won't work on live stream, in case, if you want to get fps for live feed then, you have to use your own counter. As I would have did, if, I were you.

    VideoCapture cap(0);
    double counter=0;
    clock_t t1 = clock();
    Mat frame;
    while(1)
    {
      counter++;
      cap.read(frame);
    }
    double fps = (Clock()-t1)/counter; 
    //assuming, you are on windows, clock() would give in seconds or else, it would be in ms
    

    Completely, otherway around is, save the livefeed as a video file using videowriter and then use get fps to know the fps.