Ask Your Question

OpenCV imread

asked 2015-11-03 12:17:25 -0500

acajic gravatar image

updated 2015-11-04 12:06:54 -0500

I was following these examples;

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>
   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();
  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("/home/andrija/Documents/dataset/2009_09_08_drive_0010/I1_000000.png", CV_LOAD_IMAGE_COLOR);


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?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2015-11-04 12:09:14 -0500

acajic gravatar image

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.

edit flag offensive delete link more

answered 2015-11-03 20:21:51 -0500

Willson Amalraj gravatar image

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.

edit flag offensive delete link more


Thank you for your response, I edited the question.

acajic gravatar image acajic  ( 2015-11-04 05:00:40 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2015-11-03 12:17:25 -0500

Seen: 2,229 times

Last updated: Nov 04 '15