Ask Your Question
0

The program to count number of white and black pixels in a binary image is not working.Here I paste the code i used.Please help me with a solution.

asked 2017-03-21 03:05:19 -0600

Ashiq KS gravatar image

updated 2017-03-21 03:10:19 -0600

berak gravatar image
int count_white=0;
int count_black=0;

 for (int y = 0; y < image.rows; y++) {
            for (int x = 0; x < image.cols; x++) {
                if (image.at<cv::Vec3b>(y, x) == cv::Vec3b(255, 255, 255)) {
                    count_white++;
                }
                else if (image.at<cv::Vec3b>(y, x) == cv::Vec3b(0, 0, 0)) {
                    count_black++;
                }
            }
        }
edit retag flag offensive close merge delete

Comments

1

what does image.type() return ?

(unlikely, that your binary image is Vec3b (or CV_8uC3))

berak gravatar imageberak ( 2017-03-21 03:14:28 -0600 )edit

Sorry i did not get you

Ashiq KS gravatar imageAshiq KS ( 2017-03-21 03:42:23 -0600 )edit
1
  1. you should avoid for-loops and per-pixel access, but instead use some builtin function (see answer below)
  2. when using at<someType>(y,x) , you must make sure, that the image has exactly that type, so check, don't guess !
berak gravatar imageberak ( 2017-03-21 03:49:21 -0600 )edit
1

Can you share how to obtain your binary image? Even though, I totally agree with berak's comment above; your loop works perfectly with appropriate image.

Oguzhan gravatar imageOguzhan ( 2017-03-21 04:30:30 -0600 )edit

cv::Mat Q(q.size(), q.type()); cv::threshold(q, Q, 100, 255, cv::THRESH_BINARY);

Ashiq KS gravatar imageAshiq KS ( 2017-03-21 08:27:11 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2017-03-21 03:10:35 -0600

Oguzhan gravatar image

You can use count non-zero function http://docs.opencv.org/2.4/modules/co...

For white pixels, do the same with inverted version of the image

edit flag offensive delete link more

Comments

2

note: findNonZero() only works on 1 channel images

berak gravatar imageberak ( 2017-03-21 03:12:32 -0600 )edit

Correct. should be converted to one channel first

Oguzhan gravatar imageOguzhan ( 2017-03-21 03:20:18 -0600 )edit

@Oguzhan I'm not sure you can get good result : (255,255,255) is 255 OK but what is (255,254,255) 255?

LBerger gravatar imageLBerger ( 2017-03-21 03:48:20 -0600 )edit

The image mentioned in the question is binary, so it (255,255,255) or (0,0,0)

Oguzhan gravatar imageOguzhan ( 2017-03-21 04:33:18 -0600 )edit

@Oguzhan binary image with three channels why not/

LBerger gravatar imageLBerger ( 2017-03-21 04:55:49 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-03-21 03:05:19 -0600

Seen: 1,006 times

Last updated: Mar 21 '17