C++ 如何动态更改 cv::Mat 图像尺寸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8606687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:51:54  来源:igfitidea点击:

How to change cv::Mat image dimensions dynamically?

c++opencv

提问by Rasoul

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.

我想在我的代码中声明一个 cv::Mat 对象和其他地方,更改其维度(nrows 和 ncols)。我在 OpenCV 的文档中找不到任何方法。他们总是建议在构造函数中包含维度。

采纳答案by Sam

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:

一种简单而干净的方法是使用该create()方法。您可以根据需要多次调用它,当其参数与现有缓冲区不匹配时,它将重新分配图像缓冲区:

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

文档可在https://docs.opencv.org/3.4/d3/d63/classcv_1_1Mat.html#a55ced2c8d844d683ea9a725c60037ad0 获得

回答by karlphillip

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

如果您要调整图像大小,请检查resize()

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

Mat dst使用您想要的维度和数据类型创建一个新的,然后:

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

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

除此之外还有其他插值方法cv::INTER_CUBIC,请查看文档。

回答by mevatron

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

你只是想用Size你这样计算的变量来定义它吗?

// 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);

回答by Oliver Zendel

If you know the maximum dimensions and only need to use a subrange of rows/cols from the total Mat use the functions cv::Mat::rowRange and/or cv::Mat::colRange

如果您知道最大尺寸并且只需要使用总 Mat 中的行/列的子范围,请使用函数 cv::Mat::rowRange 和/或 cv::Mat::colRange

http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-rowrange

http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-rowrange