Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change cv::Mat image dimensions dynamically?

Tags:

c++

opencv

I would like to declare an cv::Mat object and somewhere else in my code, change its dimension (nrows and ncols). I couldn't find any method in the documentation of OpenCV. They always suggest to include the dimension in the constuctor.

like image 701
Rasoul Avatar asked Dec 22 '11 16:12

Rasoul


3 Answers

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

like image 115
Sam Avatar answered Nov 04 '22 13:11

Sam


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.

like image 6
karlphillip Avatar answered Nov 04 '22 14:11

karlphillip


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);
like image 3
mevatron Avatar answered Nov 04 '22 13:11

mevatron