''' Recolor images ''' from PIL import Image import random def random_color() : ''' Returns a random RGB three-tuple ''' r = random.randrange( 0, 256 ) g = random.randrange( 0, 256 ) b = random.randrange( 0, 256 ) return ( r, g, b ) def get_width( drawing ) : ''' Returns the width of the Image represented by drawing. ''' w, h = drawing.size return w def get_height( drawing ) : ''' Returns the height of the Image represented by drawing. ''' w, h = drawing.size return h def left( spot ) : ''' Returns the coordinate immediately left of spot ''' x, y = spot return ( x - 1, y ) def right( spot ) : ''' Returns the coordinate immediately right of spot ''' x, y = spot return ( x + 1, y ) def above( spot ) : ''' Returns the coordinate immediately above spot ''' x, y = spot return ( x, y - 1 ) def below( spot ) : ''' Returns the coordinate immediately below spot ''' x, y = spot return ( x, y + 1 ) def is_inbounds( drawing, spot ) : ''' Returns spot is inbounds on drawing. ''' x, y = spot w, h = get_width( drawing ), get_height( drawing ) xgood = ( 0 <= x < w ) ygood = ( 0 <= y < h ) return ( xgood and ygood ) def get_color( drawing, spot ) : ''' If spot is inbounds on drawing, returns the color at that spot; otherwise, None. ''' if ( is_inbounds( drawing, spot ) ) : return drawing.getpixel( spot ) else : return None def is_colorable( drawing, spot, bg=(255,255,255) ) : ''' Returns whether spot is inbounds on drawing and equal to bg ''' rgb = get_color( drawing, spot ) return ( rgb == bg ) def paint( drawing, spot, c, bg=(255,255,255) ) : ''' If spot is a colorable pixel on drawing, the pixel at that spot is set to c. ''' if ( is_colorable( drawing, spot, bg ) ) : drawing.putpixel( spot, c )