Ask Your Question

handle waitkey in multi-thread application

asked 2016-09-27 03:47:42 -0500

Rok gravatar image

updated 2016-09-27 03:50:39 -0500

I have a multi-threading application written in C++ with Qt5.7 and OpenNI. It has a main thread that starts a second thread which capture frame from a .oni recording file (asus xtion pro live) does some processing and through the Qt signal-slot mechanism pass the frame to the main thread, which display it using imshow(). What I want to do is to implement a pause key, so pressing for example 'p' the processing pause. I am thinking of something like this:

void Camera::run(){
  while(!cameraStop && this->device.isValid())
      try {
        if (!buttonPause) {
            emit sigFrameImageReady(frame);
            if (cv::waitKey(1)==112){

      catch(std::exception &ex) {
         std::cerr << "getFrame()" << ex.what() << std::endl;

In this way it doesn't work, I think that's because the frame is displayed by another thread (the main one), the waitKey() here simply blocks the entire process, but if I put it in the main thread, just after imshow() in this way:

void Process::FrameImageReady(cv::Mat FrameImage)
  if (modedebug)
    cv::imshow("bgr", FrameImage);
  if (cv::waitKey(10)==112){

waitkey seems to be ignored (image displaying works fine).. any idea?

edit retag flag offensive close merge delete



please try not to mix opencv's gui with qt multithreading.

berak gravatar imageberak ( 2016-09-27 04:01:48 -0500 )edit

The Gui is just for debugging purpose, so I can afford to lose some frame and things like that, but how can i grab the key pressing?

Rok gravatar imageRok ( 2016-09-27 04:12:47 -0500 )edit

waitKey() is specific to highgui. please do not use that in a qt app.

you'll have to find a qt way to detect keypresses.

berak gravatar imageberak ( 2016-09-27 04:16:58 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2016-09-27 10:12:20 -0500

kbarni gravatar image

@berak's right. Don't mix OpenCV GUI with multithreading.

As a solutionI suggest to create a QWidgets application with a label and a button.

In the FrameImageReady function transform the FrameImage variable to QImage variable, than to QPixmap and display it on the label control (ui->label1.setPixmap(...)). Search the forum for tramsforming Mat to QImage.

Use the button control's clicked function to pause the process (cam->setButtonPause(!(getButtonPause()));).

Handling keypresses is OS dependent, so I suggest to avoid it if possible. If you still want to use it, here are some methods how to do it.

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2016-09-27 03:47:42 -0500

Seen: 2,541 times

Last updated: Sep 27 '16