Why does the namedWindow in member constructor freeze the application?

asked 2018-07-24 09:09:47 -0600

Kroll gravatar image

updated 2018-07-24 09:20:58 -0600

I prepared some working code for reproduce the issue:

main.cpp

#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <thread>

class my_class
{
public:
    my_class();

    void my_function();

private:
    int m_slider;
    std::string m_window;
    cv::Mat m_mat;
};

my_class::my_class() :
    m_slider(0),
    m_window("Separated trackbar pannel")
{
    cv::namedWindow(m_window); //<-- this line freezes app if comment then will be OK
}

void my_class::my_function()
{
    //if place here imshow then this imshow will be last line cause of constructor namedWindow
}

class my_thread_class
{
public:
    my_thread_class();
    void start();
    void stop();

private:
    std::thread m_thread;
    bool m_is_running;
    my_class m_mc;

    void loop();
};

my_thread_class::my_thread_class():
    m_is_running(false)
{
}

void my_thread_class::start()
{
    stop();
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    m_is_running = true;
    m_thread = std::thread(&my_thread_class::loop, this);
    m_thread.join();
}

void  my_thread_class::stop()
{
    m_is_running = false;
}

void my_thread_class::loop()
{
    cv::Mat frame;
    cv::VideoCapture capture("./video.mp4");
    while(m_is_running)
    {
    capture >> frame;

    if(frame.empty())
    {
        std::cout << "video_capture frame is empty" << std::endl;
        continue;
    }

        m_mc.my_function();

    cv::imshow("TEST", frame); //<-- app stops at this line if namedWindow in constructor
    cv::waitKey(30);
    }
}

int main(int argc, char *argv[])
{
    my_thread_class thread;
    thread.start();

    return 0;
}

Comments in code describe my issue. If comment line cv::namedWindow(m_window); then the video.mp4 will be displayed in window with name "TEST".

Why so?

edit retag flag offensive close merge delete

Comments

please avoid using ANY multithreading with opencv.

and all gui functions have to stay on the main thread.

berak gravatar imageberak ( 2018-07-24 09:33:17 -0600 )edit

I have the same issue with cv::namedWindow(). What do you mean by GUI have to stay in main()? What if I have several classes running and frames visualization with openCV must be executed in the background?

Farid gravatar imageFarid ( 2019-05-02 03:09:11 -0600 )edit