Error: (-215:Assertion failed) cn == 1 in function 'countNonZero'

We have a simple test in our CI that was passing with OpenCV 3.4.14:

cv::Mat testImg = cv::imread("../resources/Images/person1.png");
TensorHWCf testTensor(testImg);
cv::Mat resImg = testTensor.ToCVImage( 0 );
CHECK(cv::countNonZero(testImg != resImg) == 0);

However this test now fails with 4.5.2

../tests/graphite/dnn/TensorTest.cpp:44: ERROR: CHECK( cv::countNonZero(comp) == 0 ) THREW exception: "OpenCV(4.5.2) /usr/local/src/opencv/modules/core/src/count_non_zero.dispatch.cpp:128: error: (-215:Assertion failed) cn == 1 in function 'countNonZero'
"

Documentation suggests that “The result of comparison is an 8-bit single channel mask whose elements are set to 255 (if the particular element or pair of elements satisfy the condition) or 0.”

However the result of the comparison appears to be 3 channel.

How can I go about resolving this? It appears that a regression has been introduced.

1 Like

can’t test 3.4, but for an older 4.0.1 version:

Mat a(10,10,CV_8UC3);
Mat b(10,10,CV_8UC3);
Mat c = (a!=b);
cout << c.size() << c.type() << " " << c.channels() << endl;
[10 x 10]16 3

compare(a,b,c,CMP_NE);
cout << c.size() << c.type() << " " << c.channels() << endl;
[10 x 10]16 3

also see compare :

dst output array of type ref CV_8U that has the same size and the same number of channels as the input arrays.

i’m puzzled :wink: