nkint
nkint

Reputation: 11733

opencv: different ways to fill a cv::mat

I know that for fill a cv::Mat there is the nice cv::Mat::setTo method but I don't understand why I don't have the same effect with those pieces of code:

// build the mat
m = cv::Mat::zeros(size, CV_8UC3);
cv::cvtColor(m, m, CV_BGR2BGRA);  // add alpha channel
/////////////////////////////////////////////////////////// this works
m.setTo( cv::Scalar(0,144,0,55) );


m = cv::Mat::zeros(size, CV_8UC3);
cv::cvtColor(m, m, CV_BGR2BGRA);
///////////////////////////////////////////////////////////  this does NOT work
m = m + cv::Scalar(0,144,0,55)


m = cv::Mat::ones(size, CV_8UC3);
cv::cvtColor(m, m, CV_BGR2BGRA);
///////////////////////////////////////////////////////////  this does NOT work
m = m.mul( cv::Scalar(0,144,0,55) );


m = cv::Mat::zeros(size, CV_8UC3);
cv::cvtColor(m, m, CV_BGR2BGRA);
///////////////////////////////////////////////////////////  this works too!
cv::rectangle(tracks, 
              cv::Rect(0, 0, tracks.cols, tracks.rows), 
              cv::Scalar(0,144,0,55), 
              -1);

PS: I'm displaying those mats as an OpenGL alpha texture

Upvotes: 0

Views: 7331

Answers (2)

Michał Leon
Michał Leon

Reputation: 2316

For an aplha channel you need to use CV_8UC4, not CV_8UC3.

Upvotes: 0

littleimp
littleimp

Reputation: 1169

I guess "not work" means that the output is not the same as using setTo?

  1. When transforming with cv::cvtColor, the alpha-channel is initialized to 255. If you add or multiply anything it will stay at 255.
  2. Why do you use cv::cvtColor to transform instead of just using CV_8UC4 when creating the mat?
  3. You can't use cv::Mat::ones for multichannel initialization. Only the first channel is set to 1 when using cv::Mat::ones. Use cv::Mat( x, y, CV_8UC3, CV_RGB(1,1,1) ).

Upvotes: 2

Related Questions