# How to calculate the percentage of a specific color in an image?

I have black-and white picture like this: Can anyone tell me if it's possible to calculate the area that black color occupies in this picture, so I know what's the percentage that black color has in the whole picture?

• What have you tried? Commented Dec 8, 2018 at 16:50
• Maybe ImageMeasurements[] and if not then ImageData[] Commented Dec 8, 2018 at 17:09
• Nitpick: you don't seek a surface (like a hyperboloid of one sheet), but an area (like 1.2 square millimetres). Commented Dec 8, 2018 at 23:41

After reading Michael E2's answer, I realized that one can simply do

1 - Mean[img]


0.106198

There are several other solutions as well. There is a function called ImageLevels that counts the channels:

img = Import["https://i.sstatic.net/PdMDk.png"];
levels = ImageLevels[img]


{{0, 521982}, {1, 4393218}}

levels[[1, 2]]/(levels[[1, 2]] + levels[[2, 2]]) // N


0.106198

One could also use

neg = ColorNegate[img];
Total[neg, 2]/(Total[img, 2] + Total[neg, 2])


0.106198

or

{w, h} = ImageDimensions[img];
1 - Total[img, 2]/(w h)


0.106198

One could also explicitly get the matrix of image pixels:

pixels = Flatten@ImageData[img];
1 - Total[pixels]/Length[pixels] // N


0.106198

Just use ImageHistogram with two levels:

ImageHistogram[myImage,2, FrameTicks->True]


or

Dimensions[SplitBy[ImageData[myImage], First]][[2;;3]]


(*

{886, 1342}

*)

• So the percentage of black color is (886/1342)*100% Commented Dec 8, 2018 at 17:19

For a binary image:

img = Import["https://i.sstatic.net/PdMDk.png"];
1 - ImageMeasurements[img, "MeanIntensity"]
(*  0.106198  *)

• Thanks to this I realized that 1 - Mean[img] works... Commented Dec 9, 2018 at 13:09
• @C.E. Cool. I didn't know that. Commented Dec 9, 2018 at 13:15