How to avoid memory fragment when creating cv::Mat?

Many operation will automatically init cv::Mat on heap like cv::resize :

cv::Mat a = cv::imread("aaa.jpg");
cv::Mat b;
cv::Mat c;
cv::Mat d;
cv::resize(a, b, {256, 256});
cv::resize(a, c, {256*2, 256*2});
cv::resize(a, d, {256*3, 256*3});

This operation will alloc memory for b,c and d but may not be Continuous. In Android if this alloc/release operation happened frequently it will cause many memory fragment and may drag performance.

I’v noticed that pre-alloc memory for cv::mat using overload function cv::Mat(int h, int w, int type, void* data) for dst can avoid this matter but I must destinate image size at first and this seems not elegant.
Any better way to avoid memory fragment ? :slight_smile:

the data block of each Mat is continuous but that’s obvious.

each Mat takes a block of heap for its data. those blocks need not be adjacent to each other. that sense of “continuous” also does not apply.

it’s the allocations that cost time.

make the Mats global or static or instance members, so the Mat instances keep living.

most OpenCV calls take a dst argument and test the dst Mat for shape and element type. if both match what the function needs, the Mat’s associated data memory is reused as is. if those don’t match, the matrix is resized, i.e. reallocation.

1 Like