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.
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.)
img=cv2.imread("test.png", cv2.IMREAD_GRAYSCALE)
w_num=cv2.countNonZero(img)
cvtColor
img=cv2.imread("test.png")
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
w_num=cv2.countNonZero(img_gray)
split
to extract one channelOnly 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)
© 2024 OneMinuteCode. All rights reserved.