Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of black and white pixels (linux, imagemagik, etc)

I have black and white images (see below). How count white and black pixels (as example 30% black and 70% white, or 123456 black pixels and 39393 white pixels)?

p.s. I work in linux, what i must use? imagemagick? i prefer a command line interface program.

sample

like image 585
Anton Shevtsov Avatar asked Aug 07 '14 04:08

Anton Shevtsov


People also ask

How do you count black pixels in Imagej?

By pressing Crtl+H once the image is open, you'll get the histogram dialogue up. When you select list you'll get the number of pixels of each of the 256 shades of gray (in an 8bit image) - if you binarised the image, that will give you just values for 0 and 255 (black and white).


2 Answers

If all your pixels are either black or white, you can calculate the mean pixel brightness using ImageMagick and then multiply it by the number of pixels in the image (width x height):

convert bw.gif -format "%[nint(fx:mean*w*h)]" info:
182138

If you want the number of white and number of black pixels in two shell variables, you can do this:

read white black < <(convert bw.gif -format "%[fx:mean*w*h] %[fx:(1-mean)*w*h]" info:)

echo $white,$black
182138,153985
like image 158
Mark Setchell Avatar answered Nov 09 '22 15:11

Mark Setchell


You can use ImageMagick's histogram function to get a pixel count for each color in the image. Using your image as an example:

$ convert XPH7c.gif -define histogram:unique-colors=true \
> -format %c histogram:info:-
    153985: (  0,  0,  0,255) #000000 black
    182138: (255,255,255,255) #FFFFFF white

So, your image has 153985 black pixels, and 182138 white pixels.

like image 9
Markus Iturriaga Avatar answered Nov 09 '22 14:11

Markus Iturriaga