Ask Your Question

Plotting the pixel density of a binary image

asked 2020-10-16 08:03:14 -0500

giggon44 gravatar image


I am trying to find the density of pixels in a binary image and plot it. For example, if I pass through a binary image of 200x200 pixels, the plot x-axis would be the same size as the width of the image, while the y-axis would be the pixel density (#of white pixels) in that column. I am having trouble figuring out how to go about this, I have looked into calchist but it doesnt seem to be what I need.

Thank you.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-10-16 08:40:00 -0500

berak gravatar image

you can use cv::reduce() to 'project' the pixels onto one of the image axes, like a "spatial histogram":

// dummy data, just for visualization:
Mat img(200,300,CV_8U,Scalar(0));

// project to  x-axis
Mat proj;
reduce(img, proj, 0, REDUCE_SUM, CV_32F); // sum needs larger depth

// barchart visualization
Mat draw(img.size(), CV_8U,Scalar(0));
for (int x=0; x<draw.cols; x++) {
    float v =<float>(0,x) / 255; // sum/255 == count
    line(draw, Point(x,img.rows-1), Point(x,img.rows-int(v)), Scalar(255), 1);

image description

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2020-10-16 08:00:54 -0500

Seen: 612 times

Last updated: Oct 16 '20