''' Module manip: provides a basic pattern for image manipulation and convenience functions for some basic transformations ''' from PIL import Image def same_size( image ) : # hands back the same size of the image it was given #ow, oh = image.size # get the size of the image - it is a property so no need for () #nw, nh = ow, 15 # the new width is the same as the old width, the new height is set to 15 here #return (nw, nh) # return the new width and height in () return image.size def same_color( pixel ) : # hands back the same color as the color (pixel) it was given return pixel def same_where( spot, w, h ) : # hands back the same spot as the spot it was given return spot #return ( 1, 1 ) # always return the spot at (1,1) instead of spot --> we'll eventually get just the color # from this spot # right now, this function will hand back a duplicate of the original picture # this function has one require parameter which is an image -- original # this function has several optional parameters # size = ... if not given a function to manipulate the size of the new image, then it uses the same_size() function # color = ... if not given a function to manipulate the color of the new image, then it uses the function same_color() # where = ... if not given a function to manipulate which spot we want, then it uses the function same_where() def manip( original, size=same_size, color=same_color, where=same_where ) : ''' Provide a pattern for image manipulation. function size(): determines size of new image based on the original function color(): determines color of new image pixel based on an original pixel function where(): determines where on original to determine correspondent pixel for the new image ''' # set dimensions of the new image nw, nh = size( original ) # get a new appropriately sized image new_image = Image.new( 'RGB', ( nw, nh ) ) # fill in every pixel of the new image for nx in range( 0, nw ) : # consider every x value for the new image for ny in range( 0, nh ) : # in tandem with every y value for the image # set the spot to be filled in the new image nspot = ( nx, ny ) # determine the corresponding spot of interest in the original ospot = where( nspot, nw, ny ) # get the pixel at the ospot opixel = original.getpixel( ospot ) # determine the pixel for the new image npixel = color( opixel ) # set the nspot in the new image new_image.putpixel( nspot, npixel ) # return the filled in new image return new_image if ( __name__ == '__main__' ) : import url from manip import manip # from the module manip, import the manip function # get web image of interest link = "http://www.cs.virginia.edu/~cs1112/images/mandrill/full.png" original = url.get_image( link ) new_image = manip( original ) # pass in the original image into the manip() function # manip function will be manipulating the picture for us and create a new image new_image.show()