Python Image Module Example: How much ink on that page?

Premise:
Thought it would be fun to compute how much ink a given poster requires, per unit area of paper, when sending to the department large-format printer. The Python Imaging Library provides several modules suitable for low-level operation on image data. A simple (and probably very inefficient) script was developed to compute the white/black percentage of an image. A script like this could be used to adjust a per-poster "ink cost", which would hopefully prevent people from wasting ink. Obviously, this computation is scale-dependent, so standardized rasterization parameters would have to be set in order for the "ink cost" calculation to be fair. More generalized or efficient approaches are always welcomed.

Implementation: (when copying/pasting note whitespace in blocks)

#!/usr/bin/env python

# invoke like this: ./white.py image.png
# idea from http://www.halfbakery.com/user/lurch
import sys
import Image

# cheap and non-robust way to access first argument
file = sys.argv[1]

# open the image, load into memory
pic = Image.open( file )
imgdata = pic.load()

# extract the dimensions of the image
xsize, ysize = pic.size

# init some counters
black = 0
white = 0

# define some colors (R,G,B)
b_color = (0,0,0)
w_color = (255,255,255)

# loop over columns
for x in xrange(xsize):
        # loop over rows
        for y in xrange(ysize):
                if imgdata[x,y] == w_color:
                        white+=1
                if imgdata[x,y] == b_color:
                        black+=1
         

# compute percentages
total_pixels = xsize * ysize
pct_white = (float(white) / float(total_pixels)) * 100
pct_black = (float(black) / float(total_pixels)) * 100

# formatted printing
print "%.3f%% of image is white!" % (pct_white)
print "%.3f%% of image is black!" % (pct_black)
AttachmentSize
test.png 5.05 KB
white.py_.txt 668 bytes
#!/usr/bin/env python

# invoke like this: ./white.py image.png
# idea from http://www.halfbakery.com/user/lurch
import sys
import Image

# cheap and non-robust way to access first argument
file = sys.argv[1]

# open the image, load into memory
pic = Image.open( file )
imgdata = pic.load()

# extract the dimensions of the image
xsize, ysize = pic.size

# init some counters
black = 0
white = 0

# define some colors (R,G,B)
b_color = (0,0,0)
w_color = (255,255,255)

# loop over columns
for x in xrange(xsize):
        # loop over rows
        for y in xrange(ysize):
                if imgdata[x,y] == w_color:
                        white+=1
                if imgdata[x,y] == b_color:
                        black+=1
         

# compute percentages
total_pixels = xsize * ysize
pct_white = (float(white) / float(total_pixels)) * 100
pct_black = (float(black) / float(total_pixels)) * 100

# formatted printing
print "%.3f%% of image is white!" % (pct_white)
print "%.3f%% of image is black!" % (pct_black)

Attachments:

test.png

white.py_.txt