# Skeleton Python Implemention of Random Art # Adapted by Chris Stone from code by Andrew Farmer import random, Image, math random.seed() # MISSING CODE: plotIntensity assumes there is a function evalExpr # that given an expression, and x and y coordinates, returns a # result in [-1,1]. def plotIntensity(exp, pixelsPerUnit = 150): """Return an grayscale image of the given function""" # Create a blank canvas canvasWidth = 2 * pixelsPerUnit + 1 canvas = Image.new("L", (canvasWidth, canvasWidth)) # For each pixel in the canvas... for py in range(0, canvasWidth): for px in range(0, canvasWidth): # Convert pixel location to [-1,1] coordinates # Note that x and y conversions are not exactly the same # because increasing px goes left to right (increasing x) # but increasing py goes from top to bottom (decreasing y) x = float(px - pixelsPerUnit) / pixelsPerUnit y = -float(py - pixelsPerUnit) / pixelsPerUnit # Evaluate the expression at that point z = evalExpr(exp,x,y) # Scale [-1,1] result to [0,255]. intensity = int(z * 127.5 + 127.5) canvas.putpixel((px,py), intensity) return canvas def plotColor(redExp, greenExp, blueExp, pixelsPerUnit = 150): """Return an image constructed from the three RGB intensity functions""" redPlane = plotIntensity(redExp, pixelsPerUnit) greenPlane = plotIntensity(greenExp, pixelsPerUnit) bluePlane = plotIntensity(blueExp, pixelsPerUnit) return Image.merge("RGB", (redPlane, greenPlane, bluePlane)) # MISSING CODE: makeGray and makeColor assume there is a function # buildExpr that produces a random expression, suitable for passing # to evalExpr. def makeGray(numPics = 20): """Creates n grayscale image files named gray0.png, gray1.png, ...""" random.seed() for i in range(0,numPics): print i, ":" grayExp = buildExpr() print str(grayExp), "\n" image = plotIntensity(grayExp) image.save("gray" + str(i) + ".png", "PNG") def makeColor(numPics = 20): """Creates n color image files named color0.png, color1.png, ...""" random.seed() for i in range(0,numPics): print i, ":" redExp = buildExpr() print "red = ", str(redExp) greenExp = buildExpr() print "green = ", str(greenExp) blueExp = buildExpr() print "blue = ", str(blueExp), "\n" image = plotColor(redExp, greenExp, blueExp) image.save("color" + str(i) + ".png", "PNG") # Generate a bunch of random grayscale and color pictures. makeGray(); makeColor();