opencv / opencv

Open Source Computer Vision Library
https://opencv.org
Apache License 2.0
76.24k stars 55.63k forks source link

when create new Mat with multi-channels(i.e., 8) with the particular value(i.e. 0.9), it will raise error (error: (-215:Assertion failed) cn <= 4 in function 'scalarToRawData') #25575

Open destinyzs opened 2 weeks ago

destinyzs commented 2 weeks ago

System Information

OpenCV version: 4.1.0 Operating System / Platform: Ubuntu 20.04

Detailed description

None

Steps to reproduce

cv::Mat y = cv::Mat(100, 100, CV_32FC(8), cv::Scalar(0.9));

It will raise error:

opencv-4.1.1/modules/core/src/array.cpp:3229: error: (-215:Assertion failed) cn <= 4 in function 'scalarToRawData'

But, if i create it like this, it success.

cv::Mat y = cv::Mat(100, 100, CV_32FC(8), cv::Scalar(0.));
y.setTo(0.9);

Issue submission checklist

destinyzs commented 2 weeks ago

I check the source code, why cvSetND function will call cvScalarToRawData function. https://github.com/opencv/opencv/blob/4.x/modules/core/src/array.cpp#L2241

In cvScalarToRawData, it will check depth of Mat. https://github.com/opencv/opencv/blob/4.x/modules/core/src/array.cpp#L1511

image

In the comment of cv::Mat::Mat and setTo, both of them seem to use Mat::operator=(const Scalar& s) operator to rewrite the value of the given Mat.

    /** @overload
    @param rows Number of rows in a 2D array.
    @param cols Number of columns in a 2D array.
    @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
    CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
    @param s An optional value to initialize each matrix element with. To set all the matrix elements to
    the particular value after the construction, use the assignment operator
    Mat::operator=(const Scalar& value) .
    */
    Mat(int rows, int cols, int type, const Scalar& s);
cv::Mat &cv::Mat::setTo(cv::InputArray value, cv::InputArray mask = noArray())
Sets all or some of the array elements to the specified value. This is an advanced variant of the Mat::operator=(const Scalar& s) operator.
vpisarev commented 2 weeks ago

@destinyzs, did you try newer than 4.1.0 versions of OpenCV? 4.1.0 is super-old and is not supported anymore.

destinyzs commented 2 days ago

Not yet, but 4.1 is not a very old version. @vpisarev