How to change cv::Mat image dimensions dynamically?

If you mean to resize the image, check resize()!

Create a new Mat dst with the dimensions and data type you want, then:

cv::resize(src, dst, dst.size(), 0, 0, cv::INTER_CUBIC);

There are other interpolation methods besides cv::INTER_CUBIC, check the docs.


An easy and clean way is to use the create() method. You can call it as many times as you want, and it will reallocate the image buffer when its parameters do not match the existing buffer:

Mat frame;

for(int i=0;i<n;i++)
{
    ...
    // if width[i], height[i] or type[i] are != to those on the i-1
    // or the frame is empty(first loop)
    // it allocates new memory
    frame.create(height[i], width[i], type[i]); 
    ... 
    // do some processing
}

Docs are available at https://docs.opencv.org/3.4/d3/d63/classcv_1_1Mat.html#a55ced2c8d844d683ea9a725c60037ad0


Do you just want to define it with a Size variable you compute like this?

// dynamically compute size...
Size dynSize(0, 0);
dynSize.width = magicWidth();
dynSize.height = magicHeight();

int dynType = CV_8UC1;
// determine the type you want...

Mat dynMat(dynSize, dynType);

Tags:

C++

Opencv