It doesn't matter if your variables are global, local, class members, etc, for your question. The important fact is the lifespan of those variables. You can face memory problems if you load a lot of images at the same time. For example (let me use the C++ syntax with cv::Mat
instead of IplImage
-you should as well-):
vector<cv::Mat> images;
for(int i = 0; i < 1000000; ++i)
images.push_back(cv::imread("image.png"));
This piece of code will allocate one million matrices with one million images. Of course, this is going to take a huge amount of memory and, probably, your program will crash.
Note that in C++, you can control the lifespan of your non-static variables by limiting their scope:
for(int i = 0; i < 1000000; ++i)
{
cv::Mat im = cv::imread("image.png");
}
// im does not exist anylonger
In this code, you load an image one million times, but you only take memory for one image, because at the end of each iteration, im
is deallocated. Note that in C, with the IplImage
, you must deallocate the images by yourself with cvReleaseImage
.
So, is it important that your variables are global? No, unless you don't control their lifespan and you keep them allocated all the time, even if you don't use them.
Update: You can have local static variables whose lifespan is the entire time your app is running. These are not global (do not have a global scope) but they take memory all the time:
void someFunction()
{
static cv::Mat images[1000000];
// one millon of matrices are allocated all the time, even when someFunction ends
}