1

I get an error with the following code:

img = cv2.imread('temp.jpg')
z = cv2.countNonZero(img)
print(z)

OpenCV Error: Assertion failed (cn == 1) in cv::countNonZero, file D:\Build\OpenCV\opencv-3.1.0\modules\core\src\stat.cpp, line 1342
Traceback (most recent call last):
  File "C:\Users\hasee\Desktop\open\GuiFeaturesinOpenCV\Performance Measurement and Improvement Techniques\TestTickCount.py", line 29, in <module>
    z = cv2.countNonZero(img)
cv2.error: D:\Build\OpenCV\opencv-3.1.0\modules\core\src\stat.cpp:1342: error: (215) cn == 1 in function cv::countNonZero

But, use if I numpy function it is ok:

z = np.count_nonzero(img)
print(z)

I don't understand why.

P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
TengFei
  • 35
  • 1
  • 6
  • 6
    http://stackoverflow.com/questions/31231565/countnonzero-function-gives-an-assertion-error-in-opencv ? – al-eax Nov 15 '16 at 15:08

2 Answers2

0

When I loaded a color image, I could reproduce a similar error.

countNonZero in opencv requests the input image to be single channel. When it is color image (i.e. with 3 channels), it gives the error.

pyan
  • 3,577
  • 4
  • 23
  • 36
0

Same problem, but C++ here:

countNonZero function gives an assertion error in openCV

Solution:

The OpenCV documentation of countNonZero says:

cv2.countNonZero(src) → retval

Parameters: src – single-channel array.

Lets have a look at the imread documentation:

imread(const String& filename, int flags=IMREAD_COLOR )

Parameters: src flags -

=0 Return a grayscale image.

<0 Return the loaded image as is (with alpha channel).

If you load an image with the default flag IMREAD_COLOR, OpenCV will dynamically detect if image (and the returned mat) is colored 3-channel or 1-channel grayscale.

To solve your problem, let OpenCV convert your loaded image to grayscale automatically:

img = cv2.imread('temp.jpg',cv2.CV_LOAD_IMAGE_GRAYSCALE)
z = cv2.countNonZero(img)
print(z)

You could also convert your image after loading with cv2.cvtColor.

Your numpy code works fine because np.count_nonzero takes array_like as input, which can be a lot of crazy stuff.

Community
  • 1
  • 1
al-eax
  • 712
  • 5
  • 13
  • Thanks for the answer :) – TengFei Nov 16 '16 at 03:44
  • @TengFei You are welcome. You can vote up my answer, if it was helpful. – al-eax Nov 16 '16 at 14:54
  • Yes, your answer is helpful. I would like to vote, but this page prompted me: Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score. – TengFei Nov 17 '16 at 02:20