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

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