Ask Your Question

Revision history [back]

countNonZero isn't detecting filled bubble and returning big value

I'm working on a bubble sheet detection program in android. My program works but I have a problem detecting the first filled bubble.

  1. ⚪⚫⚪⚪⚪ >> undetected and return big value
  2. ⚫⚪⚪⚪⚪ >> detected
  3. ⚪⚪⚫⚪⚪ >> detected
  4. ⚪⚫⚪⚪⚪ >> detected
  5. ⚪⚪⚫⚪⚪ >> detected

The program itself detects all bubbles inside the paper, but it can't detect the filled bubble in the first number. When I tried printing the countNonZero, I realized that when compared to other numbers, the first one return a very big value.

I/System.out: 1. countNonZero: 766558 
I/System.out: 2. countNonZero: 364
I/System.out: 3. countNonZero: 378
I/System.out: 4. countNonZero: 378
I/System.out: 5. countNonZero: 380

And this is the code:

  for (int i = 0; i < bubbles.size(); i += options.length) {
        List<MatOfPoint> rows = bubbles.subList(i, i + options.length);

        int[][] filled = new int[rows.size()][5];

        //Loop over the sorted contours
        for (int j = 0; j < rows.size(); j++) {
            MatOfPoint col = rows.get(j);
            List<MatOfPoint> list = Arrays.asList(col);

            //Construct a mask that reveals only the current "bubble" for the question
            Mat mask = new Mat(nThresh.size(), CV_8UC1);
            Imgproc.drawContours(mask.submat(rect), list, -1, new Scalar(255, 0, 0), -1);

            //Apply the mask to the thresholded image, then count the number of non-zero pixels in the bubble area.
            Mat conjuction = new Mat(nThresh.size(), CV_8UC1);
            Core.bitwise_and(nThresh, mask, conjuction); //countNonZero counts black pixel in the mask

            int countNonZero = Core.countNonZero(conjuction);

            System.out.println("recognizeAnswers > " + i + ":" + j + " > countNonZero: " + countNonZero);

Any ideas on this?