lundi 2 avril 2018

opencv - background thread blocks UI thread

This program should allow the user to draw on the picture for few seconds(like preprocessing) and after that do some processing on the picture with ability to draw.

I create background thread to pause processing for some time. The user should be able to draw in that time.

The while loop is processing. Variable running shows if processing is active or the user can draw.

But in the code I wrote background thread blocks UI thread, although, as to my knowledge, they do not interact.

This seems like std::this_thread::sleep_for blocks all threads, but documentation says it only blocks its thread. I do not know what that means.

How to not block the UI thread?

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

bool running;
cv::Mat image;

void onMouse(int event, int x, int y, int flags, void*)
{
    running = false;
    if (event == cv::EVENT_LBUTTONDOWN)
    {
        cv::circle(image, cv::Point(x, y), 20, cv::Vec3b(0, 0, 255), CV_FILLED);
        cv::imshow("window", image);
        cv::waitKey(1);
    }
    running = true;
}

int main()
{
    running = false;

    image = cv::Mat(400, 400, CV_8UC3, cv::Scalar(0, 255, 0));
    cv::namedWindow("window", cv::WINDOW_AUTOSIZE);
    cv::imshow("window", image);
    cv::waitKey(1);

    cv::setMouseCallback("window", onMouse);

    std::thread task = std::thread([]()
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        running = true;

    });

    while (true)
    {
        if (running)
        {
            cv::imshow("window", image);
            cv::waitKey(1);
        }
    }

    task.join();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire