OpenCV element-wise matrix multiplication

c++, opencv

Solution

I would recommend converting single channel to three channels:

    Mat A = Mat::zeros(100, 200, CV_32FC1);
    Mat B = Mat::zeros(100, 200, CV_32FC3);

    // Mat C = A.mul(B); // Sizes of input arguments do not match

    Mat Afc3;
    Mat t[] = {A, A, A};
    merge(t, 3, Afc3);

    Mat C = Afc3.mul(B); // now Afc3 has 3 channels ans it is type of 32_FC3 
                         // we can multiply each elem in B by the same coef from A

But if B it is a CV_8UC3 type, it does not work because opencv would not allow to multiply Mats which have different types of pixels. In that case, convert 8UC3 to 32FC3 remebering to scale each pixel by 1/255.0 beacuse each pixel in 32FC3 has a value between 0.0 and 1.0 (and of course each pixel in 8UC3 has a value between 0 and 255).

    Mat A = Mat::zeros(100, 200, CV_32FC1);
    Mat B = Mat::zeros(100, 200, CV_8UC3);

    // Mat C = A.mul(B);

    Mat Afc3, Bfc3;
    Mat t[] = {A, A, A};
    merge(t, 3, Afc3);

    B.convertTo(Bfc3, CV_32FC3, 1/255.0);

    Mat C = Afc3.mul(Bfc3);

Problem

OpenCV docs say `A.mul(B)` is per-element multiplication. Yet the following code produces the following output, and then gives this error: ``` OpenCV Error: Sizes of input arguments do not match ``` . ``` cout << laplacian_pyramids[i][numLevels - 1 - l].rows << endl; cout << gaussian_weight_pyramids[i][l].rows << endl; cout << laplacian_pyramids[i][numLevels - 1 - l].cols << endl; cout << gaussian_weight_pyramids[i][l].cols << endl; ``` Gives: ``` 339 339 571 571 ``` Then: ``` Mat prod = gaussian_weight_pyramids[i][l].mul(laplacian_pyramids[i][numLevels - 1 - l]); ``` gives the error. I tried `Mat::multiply` to a similar effect.

Original source