Memory Management Part II. Automatic Data AllocationΒΆ

With the new interface not only explicit memory deallocation is not needed anymore, but the memory allocation is often done automatically too. That was demonstrated in the example in the beginning of the chapter when cvtColor was called, and here are some more details.

Mat and other array classes provide method create that allocates a new buffer for array data if and only if the currently allocated array is not of the required size and type. If a new buffer is needed, the previously allocated buffer is released (by engaging all the reference counting mechanism described in the previous section). Now, since it is very quick to check whether the needed memory buffer is already allocated, most new OpenCV functions that have arrays as output parameters call the create method and this way the automatic data allocation concept is implemented. Here is the example:

#include "cv.h"
#include "highgui.h"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0);
    if(!cap.isOpened()) return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame;
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    return 0;
}

The matrix edges is allocated during the first frame processing and unless the resolution will suddenly change, the same buffer will be reused for every next frame’s edge map.

In many cases the output array type and size can be inferenced from the input arrays’ respective characteristics, but not always. In these rare cases the corresponding functions take separate input parameters that specify the data type and/or size of the output arrays, like resize . Anyway, a vast majority of the new-style array processing functions call create for each of the output array, with just a few exceptions like mixChannels , RNG::fill and some others.

Note that this output array allocation semantic is only implemented in the new functions. If you want to pass the new structures to some old OpenCV function, you should first allocate the output arrays using create method, then make CvMat or IplImage headers and after that call the function.

Previous topic

Memory Management

Next topic

Algebraic Operations

This Page