Source code for rgb2gray

"""Module for converting an image to gray value. Call this module by:

   im = convert_to_gray(filename)
   
   which will return a new image by converting all the pixes in the input file to gray scale.

"""

import Image

        
[docs]def convert_to_gray(filename): """Convert the image to a 2x2 array of pixels. Then read each pixel, convert its color to gray scale and copy to the pixel array of the output image. Return the resulting image. """ im = Image.open(filename) w,h = im.size pics = im.load() im_copy = Image.new("RGB", (w,h)) pics_copy = im_copy.load() for i in range(0,w-1): for j in range(0,h-1): color = pics[i,j] gray_val = (color[0]+color[1]+color[2])/3 pics_copy[i,j] = (gray_val, gray_val, gray_val) return im_copy