Ask Your Question

Android counting white pixels in binary Mat.

asked 2013-03-02 11:32:19 -0600

PJPS gravatar image

updated 2013-03-02 12:40:55 -0600

I'm trying to count all non-black pixels in an ROI. Clearly I'm doing something wrong as it causes an exception when I try to use it.

rect = new Rect(touchX-100, touchY-100, 200, 200);
Mat roi = grayMat.submat(rect);
Imgproc.threshold(roi, roi, 240, 255, Imgproc.THRESH_BINARY);
if (Core.countNonZero(roi) > 0){

The countNonZero throws the exception

OpenCV Error: Assertion failed (src.channels() == 1 && func != 0) in int cv::countNonZero(cv::InputArray), file /home/reports/ci/slave/50-SDK/opencv/modules/core/src/stat.cpp, line 496

I'm too dumb to interpret the exception :P. I've taken a few different stabs at it and figured I'd just ask.

edit retag flag offensive close merge delete


blind stab in the dark, here :

are you sure, something like (touchX-100), or (touchY-100) does not give negative values ? do some checks, if the rect is actually totally inside the grayMat

berak gravatar imageberak ( 2013-03-02 15:04:16 -0600 )edit

Thank you for the suggestion, but that doesn't appear to be it. Cheers :-)

PJPS gravatar imagePJPS ( 2013-03-02 20:58:02 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2013-03-04 05:17:19 -0600

Andrey Pavlenko gravatar image

The countNonZero() method can process single channel images only, but it seems your grayMat isn't.

I suspect it keep a draw-able gray-scale image, i.e. of type CV_8UC4 and the channel ## 0,1,2 have the same values and the channel #3 is filled with 255 value.

I suggest you extract say the 1st channel and call the countNonZero() method:

  Mat m = new Mat();
  Core.extractChannel(grayMat, m, 0);
  int n = Core.countNonZero(m);
edit flag offensive delete link more


That was exactly it. Thank you very much!

PJPS gravatar imagePJPS ( 2013-03-04 06:55:49 -0600 )edit

Question Tools


Asked: 2013-03-02 11:32:19 -0600

Seen: 6,344 times

Last updated: Mar 04 '13