Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

c++ - countNonZero function gives an assertion error in openCV

I tried to get horizontal projection using countNonZero() function as below.

Mat src = imread(INPUT_FILE, CV_LOAD_IMAGE_COLOR);
Mat binaryImage = src.clone();
cvtColor(src, src, CV_BGR2GRAY);

Mat horizontal = Mat::zeros(1,binaryImage.cols, CV_8UC1);

for (int i = 0; i<binaryImage.cols; i++)
{
    Mat roi = binaryImage(Rect(0, 0, 1, binaryImage.rows));

    horizontal.at<int>(0,i) = countNonZero(roi);
    cout << "Col no:" << i << " >>" << horizontal.at<int>(0, i);
}

But an error is occured in the line of calling countonZero() function. Error is as follows.

    OpenCV Error: Assertion failed (src.channels() == 1 && func != 0) in cv::countNo
    nZero, file C:uilds2_4_PackSlave-win32-vc12-sharedopencvmodulescoresrcst
    at.cpp, line 549

Can somebody please point out the mistake?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assertion src.channels() == 1 means that image should have 1 channel, i.e. it has to be gray, not colored. You are calling countNonZero on roi, which is a subimage of binaryImage, which is a clone of src, which is originally colored.

I suppose you wanted to write cvtColor(binaryImage, binaryImage, CV_BGR2GRAY);. In this case it makes sense. However, I do not see you using src anywhere again, so perhaps you do not need this intermediate image. In case you do, do not call "binary", since "binary" in computer vision usually stands for black-or-white image, only two colors. Your image is "gray", since it has all shades of black and white.

Concerning your original task, Miki is right, you should use cv::reduce for it. He already gave you an example on how to use it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...