0

Rosanswers logo

I was following these examples; http://wiki.ros.org/action/login/image_transport/Tutorials/PublishingImages

More specifically, let's look at this piece of code:

   1 #include <ros/ros.h>
   2 #include <image_transport/image_transport.h>
   3 #include <opencv2/highgui/highgui.hpp>
   4 #include <cv_bridge/cv_bridge.h>
   5 
   6 int main(int argc, char** argv)
   7 {
   8   ros::init(argc, argv, "image_publisher");
   9   ros::NodeHandle nh;
  10   image_transport::ImageTransport it(nh);
  11   image_transport::Publisher pub = it.advertise("camera/image", 1);
  12   cv::Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
  13   cv::waitKey(30);
  14   sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();
  15 
  16   ros::Rate loop_rate(5);
  17   while (nh.ok()) {
  18     pub.publish(msg);
  19     ros::spinOnce();
  20     loop_rate.sleep();
  21   }
  22 }

I changed it a little:

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>

int main(int argc, char** argv) { ros::init(argc, argv, "image_publisher"); ros::NodeHandle nh;

ros::Rate loop_rate(5);
while (nh.ok()) {
    cv::imread(&quot;/home/andrija/Documents/dataset/2009_09_08_drive_0010/I1_000000.png&quot;, CV_LOAD_IMAGE_COLOR);
    cv::waitKey(100);

    ros::spinOnce();
    loop_rate.sleep();
}

}

It's not designed to do anything useful. But it causes unbounded memory growth every time I run this code. I can stop memory growth only by commenting out the OpenCV's imread method call. The memory starts at ~10MB and within 10 seconds it's over 150MB and continues to rise monotonically.

Can anyone explain this? Why is this happening? How can I read images in any kind of loop and prevent memory leaks?


Originally posted by acajic on ROS Answers with karma: 36 on 2015-11-03

Post score: 0

2 Answers2

0

Rosanswers logo

OpenCV's imread will load images as Mat. Unlike IplImage* the Mat object will automatically be released, once it goes out of the scope in which it was declared.

That being said using,

cv::Mat src = cv::imread('xyz.jpg', CV_LOAD_IMAGE_COLOR); src.release();

will also release the memory.


Originally posted by Willson Amalraj with karma: 206 on 2015-11-03

This answer was NOT ACCEPTED on the original site

Post score: 1


Original comments

Comment by acajic on 2015-11-04:
Thank you for your response, I edited the question.

0

Rosanswers logo

I managed to get rid of this problem, but I don't know exactly how.

I suspect it was caused by having independent installation of OpenCV and the one that is used by ROS. After I uninstalled OpenCV and reinstalled ROS, everything seemed to work fine.


Originally posted by acajic with karma: 36 on 2015-11-04

This answer was ACCEPTED on the original site

Post score: 0