Home > Net >  Thread.Sleep() doesn't work with Cv2.ImShow, OpenCvSharp, C#
Thread.Sleep() doesn't work with Cv2.ImShow, OpenCvSharp, C#

Time:06-28

Very Simple C# Winforms App, OpenCVSharp4, Thread.Sleep() doesn't work. It seems like (as I guess) Cv2 cannot be used in multiple threads, eg, one thread create NamedWindow, another thread ImShow. But this simple code below is still confusing.

    private void button1_Click(object sender, EventArgs e)
    {
        VideoCapture video = new VideoCapture("E:/RankingBack.mp4");
        Mat frame = new Mat();

        while (true)
        {
            video.Read(frame);
            Cv2.ImShow(" ", frame);
            //Cv2.WaitKey(33);  // WORKS
            Thread.Sleep(33);   // DOES NOT WORK
        }

        frame.Dispose();
        video.Release();
        Cv2.DestroyAllWindows();

    }

CodePudding user response:

waitKey's purpose is not waiting, it's to spin the GUI event loop that OpenCV uses. If you don't call it, OpenCV's GUI doesn't work.

You're using C# and WinForms already (judging by the tags), so you should use WinForms instead of imshow. OpenCV does its own GUI event handling, which may conflict with other GUI toolkits that are being used in the same program.

OpenCV's GUI functions are generally not safe to call from threads because some GUI backends don't allow that. That's irrelevant though because...

You do not have a "thread" here. You have the handler for a button click event. That's executed by the event loop of your WinForms application. That happens in the main thread that is always there in every process. That is not a spawned thread.

  • Related