# Histogram: Count black pixel per column

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 close merge delete

Sort by » oldest newest most voted

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.

more

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!

Official site

GitHub

Wiki

Documentation