2

これは、別のスレッドでコンテンツを含む HighGui ウィンドウを生成するために使用するクラスです。

class Capture {
private:
  bool running;
  std::thread thread;
  cv::Mat background;
  void loop() {
    while (running) {
      cv::imshow("sth",background);
      cv::waitKey(settings::capture_wait_time);
    }
  }
  public:
   Capture()  :
     running {false},
     thread {},
     background { 800, 800,  CV_8UC3, cv::Scalar{255,0,255}} {
       cv::namedWindow("sth");  
   }
   inline ~Capture() {
     if (running) stop(); // stop and join the thread
     cv::destroyWindow("sth");
   }
   void run() {
     if (!running) {
       running = true;
       thread = std::thread{[this]{loop();}};
     }
   }
   inline void join() { if (thread.joinable()) thread.join(); };
   inline void stop() {
     running = false;
     if (thread.joinable()) thread.join();
   }
};

// main
Capture cap;
cap.run();
// ... 

問題は、ウィンドウが常に黒くなることです (この場合、ウィンドウは紫になるはずです)。私は明らかにここに何かが欠けています....

4

1 に答える 1

2

別のスレッドでウィンドウを作成できないようです。また、他のスレッドでメンバー関数を呼び出す方法が間違っているようです。

このコードを見てください。別のスレッドで毎秒変化する画像を表示し、5 秒後に戻ります。

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

using namespace std;
using namespace cv;

class Capture {
private:
    bool running;
    std::thread thread;
    cv::Mat background;
    void loop() {

        while (running) {
            cv::imshow("sth", background);
            cv::waitKey(1000);

            Scalar color(rand()&255, rand()&255, rand()&255);
            background.setTo(color);
        }
    }
public:
    Capture() :
        running{ false },
        thread{},
        background{ 800, 800, CV_8UC3, cv::Scalar{ 255, 0, 255 } } {
    }
    inline ~Capture() {
        if (running) stop(); // stop and join the thread
    }
    void run() {
        if (!running) {
            running = true;
            thread = std::thread{ &Capture::loop, this };
        }
    }
    inline void join() { if (thread.joinable()) thread.join(); };
    inline void stop() {
        running = false;
        if (thread.joinable()) {
            thread.join();
        }
    }
};

int main()
{
    Capture cap;
    cap.run();

    std::this_thread::sleep_for(std::chrono::milliseconds(5000));

    cap.stop();

    return 0;
}
于 2016-02-04T00:26:00.617 に答える