About CountNonZero in opencv

Asked 2 years ago, Updated 2 years ago, 89 views

The following program using CountNonZero in opencv

#-*-coding:utf-8-*-
import cv2
import numpy as np

w_num = 0

img=cv2.imread("detect_0_0.jpg")
w_num=cv2.CountNonZero(img)
print("%d"%w_num)

When I ran

Traceback (most recent call last):
  File "wcount2.py", line 9, in <module>
    w_num = cv2.cv.CountNonZero(img)
TypeError: CvArr argument 'arr' must be IplImage, CvMat or CvMatND. Use 
fromarray() to convert numpy arrays to CvMat or cvMatND

The error occurred.How do I deal with this?
The programming language is python.

python opencv

2022-09-30 16:28

1 Answers

The argument for countNonZero() is "single-channel array".
imread seems to have a tricolor (BGR) channel by default.

To obtain a single channel array, you can use the following methods:
(The link is an OpenCV document, but there is no description for Python.Arguments may vary slightly.)

Specify

to specify to load images in ImpreadModes
img=cv2.imread("test.png", cv2.IMREAD_GRAYSCALE)
w_num=cv2.countNonZero(img)

Convert with cvtColor

img=cv2.imread("test.png")
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
w_num=cv2.countNonZero(img_gray)

split to extract one channel

Only certain colors will be processed, but if they were originally grayscale or binary images, the results should be the same as above.

img=cv2.imread("test.png")
img_ch0=cv2.split(img)[0]
w_num=cv2.countNonZero(img_ch0)


2022-09-30 16:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.