Ask Your Question
1

Histogram: Count black pixel per column

asked 2012-11-16 10:24:28 -0600

flohei gravatar image

Hi guys,

I'm just getting started with OpenCV and I was wondering if it's possible, using calcHist, to create a histogram that counts all the black pixel per column in a binary image. By column I mean every single pixel column of the image, so that I would use image.width bins. Every bin should then have a value like 60, 80, 1000, whatever, depending of how many of the pixels in that column were black. Is there a way to use the OpenCV method or do I have to implement it myself?

Thanks a lot!
–f

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
2

answered 2012-11-17 07:32:20 -0600

Michael Burdinov gravatar image

updated 2012-11-18 05:01:28 -0600

This is not really a histogram so calcHist won't really help you. But you could use other functions of OpenCV for this task. Shortest way will be:

int* histogram = new int[width]; 
for(i=0; i<width; i++)
   histogram[i] = height - countNonZero(yourImage.col(i));

Brief explanation: Function col(i) creates Mat from i-th column of your image (without memory allocations). countNonZero counts amount of non-black pixels. And since you are interested in black pixels you just do height of your image minus non-black pixels.

This is the shortest way but not the fastest because memory access along columns of image is slow. Better memory access (and so the speed) can be achieved by:

Mat histogram(Size(width,1), CV_32S, Scalar(0));
for(j=0; j<height; j++)
    histogram += (yourImage.row(j)==0);
histogram /= 255;

Brief explanation: (yourImage.row(j)==0) returns binary image. Every pixel that was 0 in your image will be set to 255 (this is the reason I divided values of histogram by 255), and the rest will be set to 0. You accumulate all this into your histogram.

edit flag offensive delete link more

Comments

Had a typo in second code. Sorry. See edited version.

Michael Burdinov gravatar imageMichael Burdinov ( 2012-11-18 05:07:23 -0600 )edit

Thanks, Michael. The second example does crash with OpenCV Error: Bad argument on the line histogram += …. But the first one does work fine for me. Thank you!

flohei gravatar imageflohei ( 2012-11-19 04:22:58 -0600 )edit

Question Tools

Stats

Asked: 2012-11-16 10:24:28 -0600

Seen: 3,037 times

Last updated: Nov 18 '12