OpenCv C++,将传入的垫子分配给函数中的垫子失败

OpenCv C++, Assigning a passed-in Mat to Mat within function fails

本文关键字:函数 失败 子分配 C++ OpenCv      更新时间:2023-10-16

我有一个函数,resizeToShortSide,它需要一个垫子并将其短边调整为指定的值。为了调整大小,我设置了一个目标垫子,调整大小垫子,执行调整大小,然后将调整大小的垫子分配给输入垫子,垫子。此操作已成功发生。

但是,当函数结束时,传递给函数的 Mat 再次是其原始大小,就好像没有发生对调整大小的 Mat 的分配一样!OpenCv Mat总是通过引用传递,所以我不确定为什么它表现得像是Mat的副本被传递。这是有问题的函数...

void resizeToShortSide(Mat mat, int shortSide, int resamplingMethod)
{
    //determine which side is the short side
    bool shortSideIsRows;
    if (mat.rows <= mat.cols) {
        shortSideIsRows = true;
    } else {
        shortSideIsRows = false;
    }
    //caluculate the size of the long side
    Size outputSize;
    if (shortSideIsRows) {
        int cols = (shortSide / (float) mat.rows) * mat.cols;
        int rows = shortSide;
        outputSize = Size(cols, rows);
    } else {
        int rows = (shortSide / (float) mat.cols) * mat.rows;
        int cols = shortSide;
        outputSize = Size(cols, rows);
    }
    //setup a destination mat
    Mat resizedMat(outputSize, CV_8UC4);
    //resize
    if (resamplingMethod == BashSettings::ResamplingMethod::NearestNeighbor)
        resize(mat, resizedMat, outputSize, 0, 0, INTER_NEAREST);
    else
        resize(mat, resizedMat, outputSize);    //defaults to INTER_LINEAR
    //assign mat to resized mat
    mat = resizedMat;
    qDebug() << "resize to short side " << shortSide;
    qDebug() << "resized mat width, height " << resizedMat.cols << ", " << resizedMat.rows;
    qDebug() << "input mat width, height " << mat.cols << ", " << mat.rows;
    qDebug() << " ";
}

Mat类本身包含一些"标头信息"以及指向UMatData对象的指针。 UMatData处理引用计数。 遗憾的是,MatSize size定义位于Mat对象中。 由于函数resizeToShortSide按值Mat,因此函数返回时无法更新大小。 您仍然需要通过引用传递Mat。 下面是Mat类定义的相关部分:

class CV_EXPORTS Mat
{
     ...
    //! interaction with UMat
    UMatData* u;
    MatSize size;
    MatStep step;
    ...
}

请注意,cv::resize 函数是使用 InputArrayOutputArray 参数定义的。

void cv::resize(InputArray  src, OutputArray dst, Size  dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR) 

这些 InputArrayOutputArray 类实现包装Mat引用的构造函数,因此更改可以保留到dst

_InputArray(const Mat& m);
_OutputArray(Mat& m);

您将mat传递给按值函数,通过引用重试或返回resizeMat