OpenCV imread
I was following these examples; http://wiki.ros.org/action/login/imag...
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("/home/andrija/Documents/dataset/2009_09_08_drive_0010/I1_000000.png", 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?