Ask Your Question

How to update cv::namedwindow in multi-threading environment?

asked 2019-03-30 04:49:03 -0600

JeyP4 gravatar image

If 1 callback receives an image and performs some image-processing. How can the output image be shown in multi-threading environment? By multi-threading I mean, if that particular callback(depthCallback) can be invoked by more than one thread.

And, one more query: Is using waitkey(1), optimal for real-time application?

class storedData {
    cv::Mat im, depth, outIm;
    void imCallback(const sensor_msgs::CompressedImageConstPtr& msgIm) {
      im = cv::imdecode(cv::Mat(msgIm->data),3);

    void depthCallback(const sensor_msgs::CompressedImageConstPtr& msgDepth)
      depth = cv::imdecode(cv::Mat(msgDepth->data),0);

      //    Performs something using both images(im & depth), Result : outIm    //

      cv::imshow("view", outIm);
int main(int argc, char **argv)
  ros::init(argc, argv, "PredictiveDisplay");
  ros::NodeHandle nh;
  storedData obj;
  cv::namedWindow("view", 0);

  ros::Subscriber subIm = nh.subscribe("/image", 2, &storedData::imCallback, &obj);
  ros::Subscriber subDepth = nh.subscribe("/depth", 2, &storedData::depthCallback, &obj);

  ros::AsyncSpinner spinner(2);

edit retag flag offensive close merge delete


In single threading ros::spin(), above code runs well. And update image normally. In multi-threading ros::AsyncSpinner spinner(2), node gets hang, and can't be stopped by Ctrl+C.

JeyP4 gravatar imageJeyP4 ( 2019-03-30 04:51:46 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2019-03-30 05:12:39 -0600

berak gravatar image

updated 2019-03-30 05:44:34 -0600

you should never try to do that !

opencv's gui functions, like namedWindow, imshow, waitKey HAVE to stay on the main thread.

and be careful with multithreading in general. most of opencv's functionality is NOT THREADSAFE by design !

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2019-03-30 04:49:03 -0600

Seen: 2,130 times

Last updated: Mar 30 '19