Reputation: 1299
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.
Upvotes: 10
Views: 5697
Reputation: 11
A less smart, but more intuitive option:
$ convert XPH7c.gif XPH7c.txt
$ grep "white" XPH7c.txt | nl | tail -1
182138 514,632: (255,255,255,255) #FFFFFF white
$ grep "black" XPH7c.txt | nl | tail -1
153985 530,632: ( 0, 0, 0,255) #000000 black
Explanation:
1) Convert gif file to txt file (human readable list providing each pixel coordinate and respective color)
0,0: ( 0, 0, 0,255) #000000 black
1,0: ( 0, 0, 0,255) #000000 black
2,0: (255,255,255,255) #FFFFFF white
(...)
530,632: ( 0, 0, 0,255) #000000 black
2) List all "black" and "white" pixels using grep (display only last line info with tail -1)
3) Additional step -- Display only the desired data using awk or other similar tool
$ grep "black" XPH7c.txt | nl | tail -1 | awk '{print $8 ": " $1}'
black: 153985
Upvotes: 1
Reputation: 208003
Another way to do this is to clone the image and set all the pixels in the cloned image to black, then calculate the Absolute Error with respect to the original image like this:
convert XPH7c.gif \( +clone -evaluate set 0 \) -metric AE -compare -format "%[distortion]" info:
182138
That tells you that there are 182,138 pixels in the original image that differ from the totally black cloned image, i.e. 182,138 non-black (white) pixels.
Upvotes: 1
Reputation: 208003
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
Upvotes: 6
Reputation: 176
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.
Upvotes: 10