Ask Your Question
2

Multiplication between Mat and Scalar

asked 2016-06-13 17:05:32 -0600

akihiko gravatar image

For a given mask image (binary cv::Mat M), I'd like to color (cv::Scalar C) the white pixels of M. In general, I think this problem is an element-wise multiplication between cv::Mat and cv::Scalar, like:

M2 = M*C

where I am expecting:

[0 1 0 ...]                     [Scalar(0,0,0) Scalar(b,g,r) Scalar(0,0,0) ...]
[0 1 1 ...]  * Scalar(b,g,r) =  [Scalar(0,0,0) Scalar(b,g,r) Scalar(b,g,r) ...]
[0 0 0 ...]                     [Scalar(0,0,0) Scalar(0,0,0) Scalar(0,0,0) ...]

but actually there is no definition of operator* between cv::Mat and cv::Scalar. What is a good alternative?

Computing an image for each channel (i.e. M*b, M*g, M*r) and then compose a single image by cv::merge would be a solution, but I feel it might not be computationally efficient. (or is this a best way?)

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2016-06-13 17:35:56 -0600

Tetragramm gravatar image

updated 2016-06-13 17:53:12 -0600

I think what you want is probably the setTo function. You create a 3 channel image, then call setTo on that object, passing the scalar and the mask. This is assuming your mask image is one channel and you want a three channel image, then this would be the fastest way.

If your binary mask image is already three channel, then the multiply(src1, src2, dst) function will take a scalar in src1 or src2.

sample code:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv){

    Mat M=Mat::eye(3,3,CV_8UC1);
    Mat M2 = Mat(3,3,CV_8UC3,Scalar(0,0,0));
    cout << "M:\n" << M << endl;

    M2.setTo(Scalar(127,128,255),M);
    cout << "\nM2:\n" << M2 << endl;
    imshow("img", M);
    waitKey(0);
}

output:

M:
[  1,   0,   0;
   0,   1,   0;
   0,   0,   1]

M2:
[127, 128, 255,   0,   0,   0,   0,   0,   0;
   0,   0,   0, 127, 128, 255,   0,   0,   0;
   0,   0,   0,   0,   0,   0, 127, 128, 255]
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-06-13 17:05:32 -0600

Seen: 3,915 times

Last updated: Jun 13 '16