In [1]:
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt

Create the image.

In [2]:
n_white, n_gray, n_black = 20, 50, 30
in_white = np.zeros(n_white).reshape((n_white / 10, 10))
in_gray = 125 * np.ones(n_gray).reshape((n_gray / 10, 10))
in_black = 255 * np.ones(n_black).reshape((n_black / 10, 10))
img = np.vstack([in_white, in_gray, in_black])
plt.imshow(img, cmap='bone', interpolation='nearest')
plt.colorbar()
Out[2]:
<matplotlib.colorbar.Colorbar instance at 0x10df31200>

Calculate how many pixels are in the white, gray, and black ranges.

In [3]:
lower = 255 / 3
upper = 2 * lower
black = np.sum(img >= upper)
gray = np.sum(np.logical_and(lower <= img, img < upper))
white = np.sum(img < lower)
In [4]:
all = img.size
print "Total pixels: %d" % all
print "White pixels: %d (%5.2f%%)" % (white, 100.0*white/all)
print "Black pixels: %d (%5.2f%%)" % (black, 100.0*black/all)
print "Gray pixels:  %d (%5.2f%%)" % (gray, 100.0*gray/all)
Total pixels: 100
White pixels: 20 (20.00%)
Black pixels: 30 (30.00%)
Gray pixels:  50 (50.00%)
In [5]:
assert(n_white == white)
assert(n_gray == gray)
assert(n_black == black)