cfischer
cfischer

Reputation: 24912

OpenCV Mat::ones function

According to the docs, this function should return a Mat with all elements as ones.

Mat m = Mat::ones(2, 2, CV_8UC3);

I was expecting to get a 2x2 matrix of [1,1,1]. Instead, I got this:

[1, 0, 0] [1, 0, 0]
[1, 0, 0] [1, 0, 0]

Is this the expected behaviour?

Upvotes: 19

Views: 24749

Answers (1)

Alexey
Alexey

Reputation: 5978

It looks like Mat::ones() works as expected only for single channel arrays. For matrices with multiple channels ones() sets only the first channel to ones while the remaining channels are set to zeros.

Use the following constructor instead:

Mat m = Mat(2, 2, CV_8UC3, Scalar(1,1,1));
std::cout << m;

Edit. Calling

Mat m = Mat::ones(2, 2, CV_8UC3); 

is the same as calling

Mat m = Mat(2, 2, CV_8UC3, 1); // OpenCV replaces `1` with `Scalar(1,0,0)`

Upvotes: 23

Related Questions