Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

[Help - OpenCV C++] Thread loop reconnects the camera

Hello, I had a problem when I started getting to know OpenCV in C ++.

First, I successfully connected and displayed the IP camera via RTSP. I disconnected in a short period of time (<30s), it automatically reconnected. But the time for large disconnection (> = 30s), the program interrupts and ends. Because I want to make the stream automatically reconnect constantly without ever interrupting the program. When the camera is on, frames are pushed into the queue and then displayed (imshow). If the frame is empty, I leave the value "sleep (10)" and keep waiting until a new frame is written into the queue to display.

Unfortunately I am not good at C ++ code and have only started learning for a week.

This is the first code I found out. I only managed to temporarily disconnect in the short time that I looked online

#include <iostream>
#include <thread>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

class Camera
{

    public:
        static void display(int i)
        {
            VideoCapture cap(0);

            if (!cap.isOpened())
            {
                cout << "Disconnect Camera" << endl;
                exit(-1);
            }

            Mat frame;
            namedWindow("Display Camera", WINDOW_AUTOSIZE);
            while (true)
            {
                bool success = cap.read(frame);
                if (!success)
                {
                    cout << "Disconnected" << endl;
                    break;
                }
                imshow("Display Camera", frame);
                if (waitKey(1) >= 0)
                {
                    break;
                }
            }
        }
};

int main()
{
    thread myThread(bind(Camera::display, 0));
    myThread.join();

    return 0;
}

And i found a document at this link. But, I can't fix how to move the code from the run function to main as in the comment mentioned HERE

I hope someone can help my problem. All suggestions and help are greatly appreciated. Thank you very much :D!