from __future__ import division import numpy as np from matplotlib import pyplot as plt 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() 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) 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) assert(n_white == white) assert(n_gray == gray) assert(n_black == black)