OpenCV 通过子矩阵改变矩阵

OpenCV changing matrix via submatrixes

我想通过子矩阵逐步改变我的矩阵。但是像素值没有变化。输出像素值与输入像素值相同。我的 "wavenoise" 功能也很好用。

这是我的代码:

cv::Mat wave_trans = Mat::zeros(nr, nc, CV_64FC1);
for (int i = 0; i < L; i++){
    Range Hhigh = Range(nc / 2, nc-1);
    Range Hlow = Range(0, nc / 2 - 1);
    Range Vhigh = Range(nr / 2, nr-1);
    Range Vlow = Range(0, nr / 2 - 1);


    Mat wave_trans_temp1 = Mat(wave_trans, Vlow, Hhigh);
    wave_trans_temp1 = wavenoise(wave_trans_temp1, NoiseVar);


    Mat wave_trans_temp2 = Mat(wave_trans, Vhigh, Hlow);
    wave_trans_temp2 = wavenoise(wave_trans_temp2, NoiseVar);


    Mat wave_trans_temp3 = Mat(wave_trans, Vhigh, Hhigh);
    wave_trans_temp3 = wavenoise(wave_trans_temp3, NoiseVar);

    nc = nc / 2;
    nr = nr / 2;
}

使用 cv::Mat 时,请务必记住它是基础数据数组的引用计数句柄。

因此,赋值运算符有两个(为了我们的目的)重载,它们具有截然不同的行为。

第一个取矩阵:

cv::Mat& cv::Mat::operator= (const cv::Mat& m)

Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented.

第二个采用矩阵表达式:

cv::Mat& cv::Mat::operator= (const cv::MatExpr& expr)

As opposite to the first form of the assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result.

因此,表达式如

nc = nc / 2;

将更新 nc 的值,因为 nc / 2cv::MatExpr.

然而,当我们分配一个 cv::Mat,例如从某个函数返回的

cv::Mat foo(cv::Mat m);

// ...
void baz(cv::Mat input) {
     cv::Mat bar(input);

     bar = foo(bar); // bar now points to whatever foo returned, input is not changed
}

要解决此问题,您可以使用 cv::Mat::copyTo 将函数的结果复制到 submatrix/view。

例如

Mat wave_trans_temp3 = Mat(wave_trans, Vhigh, Hhigh);
wavenoise(wave_trans_temp3, NoiseVar).copyTo(wave_trans_temp3);