Gopiraj
Gopiraj

Reputation: 657

Initialize a Multi-Channel OpenCV Mat

I have to initialize a multi-channel OpenCV matrix. I'm creating the multi-channel matrix like this

cv::Mat A(img.size(), CV_16SC(levels));

where levels is the number of channels in the matrix can be anywhere from 20 - 300. I cannot initialize this matrix other than zero.

If I initialize the matrix like this

cv::Mat A(img.size(), CV_16SC(levels), Scalar(1000));

I'm getting an error stating "Assertion failed (cn <= 4) in cv::scalarToRawData". Which seems like we can initialize values only up to 4 channels

Is there any other method available in OpenCV to initialize this multi-channel matrix or I have to manually initialize the values?

Edit: I have done the following to initialize this multi-channel matrix. Hope this helps those who come across the same issue

for (int j = 0; j < img.rows; ++j) for (int i = 0; i < img.cols; ++i)
{
    short *p = A.ptr<short>(j) +(short)i*levels;
    for (int l = 0; l < levels; ++l)
    {
        p[l] = 1000;
    }
}

Upvotes: 1

Views: 1916

Answers (1)

HansHirse
HansHirse

Reputation: 18895

I was trying to use OpenCV's Vec_ and Mat_ template classes, because of this Mat_ constructor. Unfortunately, I couldn't find a working solution. All attempts lead to the same error, you already came across with. So, my guess would be, the underlying OpenCV implementation just does not support such actions, even on custom derived types.

Certainly, you have your own idea to work-around this. Nevertheless, I wanted to provide the shortest (and hopefully most efficient) solution, I could think of:

const int levels = 20;
const cv::Size size = cv::Size(123, 234);

const cv::Mat proto = cv::Mat(size, CV_16SC1, 1000);

std::vector<cv::Mat> channels;
for (int i = 0; i < levels; i++)
    channels.push_back(proto);

cv::Mat A;
cv::merge(channels, A);

Upvotes: 3

Related Questions