# How to calculate surface of specific color?

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

• What have you tried? – C. E. Dec 8 '18 at 16:50
• Maybe ImageMeasurements[] and if not then ImageData[] – Michael E2 Dec 8 '18 at 17:09
• Nitpick: you don't seek a surface (like a hyperboloid of one sheet), but an area (like 1.2 square millimetres). – Andreas Rejbrand Dec 8 '18 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.stack.imgur.com/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% – Cro Simpson2.0 Dec 8 '18 at 17:19

For a binary image:

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

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