''' Purpose: provide means of converting an image to grayscale ''' from PIL import Image def average( original ) : ''' produce a grayscale ''' # get image dimensions ow, oh = original.size # get the dimensions of the original nw, nh = ow, oh # new image has same dimensions # create new image new_image = Image.new( 'RGB', (nw, nh ) ) # consider every pixel for nx in range( 0, nw ) : # consider every possible x value for ny in range( 0, nh ) : # consider every possible y value # get spots of interest nspot = ( nx, ny ) ospot = ( nx, ny ) # get color of the original pixel opixel = original.getpixel( ospot ) r, g, b = opixel # get the gray equivalent a = ( r + g + b ) // 3 npixel = ( a, a, a ) # set new image pixel color new_image.putpixel( nspot, npixel ) # return the result return new_image def ntsc( original ) : ''' produce a grayscale pixels to their monochrome luminances, using NTSC formula mapping (r, g, b) to (m, m, m), where m = .299r + .587g + .114b ''' # get image dimensions ow, oh = original.size # get the dimensions of the original nw, nh = ow, oh # new image has same dimensions # create new image new_image = Image.new( 'RGB', (nw, nh ) ) # consider every pixel for nx in range( 0, nw ) : # consider every possible x value for ny in range( 0, nh ) : # consider every possible y value # get spots of interest nspot = ( nx, ny ) ospot = ( nx, ny ) # get color of the original pixel opixel = original.getpixel( ospot ) r, g, b = opixel # get the gray equivalent m = int( .299*r + .587*g + .114*b ) npixel = ( m, m, m ) # set new image pixel color new_image.putpixel( nspot, npixel ) # return the result return new_image if ( __name__ == '__main__' ) : import url import grayscale # get web image of interest link = "http://www.cs.virginia.edu/~cs1112/images/mandrill/full.png" im = url.get_image( link ) # get grayed versions grayed1 = grayscale.average( im ) grayed1.show() grayed2 = grayscale.ntsc( im ) grayed2.show()