''' Purpose: support image black-and-white transformation ''' def bw( opixel ) : ''' Returns a new pixel whose RRB values are either (0, 0, 0) or (255, 255, 255). Returns (0, 0, 0) if the average of RGB values for opixel is closer to 0 than 255; otherwise, it returns (255, 255, 255) ''' # if the color of opixel is closer to 0, then return (0,0,0) # else, return (255,255,255) # get the amount of red, green, and blue components from opixel red, green, blue = opixel # the amount of each color component is 0-255 inclusive # get the sum of the amount of red, green, and blue # then divide by 3 to get the average --> is this average closer to 0 or 255? average = ( red + green + blue ) / 3 if ( average < 255 / 2 ): # if the average is closer to 0 (less than half of 255) return (0, 0, 0) else: # otherwise, the average is closer to 255 if its at least halfway to 255 return (255, 255, 255) if ( __name__ == '__main__' ) : import url from manip import manip # 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, color=bw ) new_image.show()