#---------------------------------------------------------------------- # Image filtering # Matrix is a 3x3 grid of multipliers for the neighboring pixels # around each pixel from the source image. The 3x3 grid is represented # by a list of lists: [[_,_,_],[_,_,_],[_,_,_]]. # See page 292 in the Companion. # Copyright (C) March 27, 2017 -- Dr. William T. Verts #---------------------------------------------------------------------- def Filter (Canvas, Matrix, Scale=1, Offset=0): # NewCanvas = makeEmptyPicture(getWidth(Canvas),getHeight(Canvas)) NewCanvas = duplicatePicture(Canvas) for Y in range(getHeight(Canvas)): # Scan all rows for X in range(getWidth(Canvas)): # Scan all columns TotalR = 0 TotalG = 0 TotalB = 0 for YY in range(max(Y-1,0),min(Y+2,getHeight(Canvas))): # Scan Y neighbors, clip to top & bottom for XX in range(max(X-1,0),min(X+2,getWidth(Canvas))): # Scan X neighbors, clip to left & right PX = getPixel(Canvas,XX,YY) R = getRed(PX) G = getGreen(PX) B = getBlue(PX) Yindex = YY - Y + 1 # Convert Canvas-relative coordinates back Xindex = XX - X + 1 # into Matrix-relative coordinates Multiplier = Matrix[Yindex][Xindex] TotalR = TotalR + R * Multiplier TotalG = TotalG + G * Multiplier TotalB = TotalB + B * Multiplier TotalR = TotalR / Scale + Offset TotalG = TotalG / Scale + Offset TotalB = TotalB / Scale + Offset NewColor = makeColor(TotalR,TotalG,TotalB) PX = getPixel(NewCanvas,X,Y) setColor(PX,NewColor) repaint(NewCanvas) return NewCanvas #---------------------------------------------------------------------- def Main(): Filename = pickAFile() Canvas = makePicture(Filename) show(Canvas) # Uncomment the line for the desired filtering function below: # Canvas = Filter(Canvas, [[-1, 0,-1],[ 0, 7, 0],[-1, 0,-1]], 3, 0) # Focus # Canvas = Filter(Canvas, [[-1,-1,-1],[-1, 8,-1],[-1,-1,-1]], 1, 0) # Edge Detect # Canvas = Filter(Canvas, [[-1,-1,-1],[-1, 8,-1],[-1,-1,-1]], -1, 255) # Edge Detect and Negate # Canvas = Filter(Canvas, [[ 1, 0, 0],[ 0, 0, 0],[ 0, 0,-1]], 1, 128) # Emboss UL # Canvas = Filter(Canvas, [[-1, 0, 0],[ 0, 0, 0],[ 0, 0, 1]], 1, 128) # Emboss LR # Canvas = Filter(Canvas, [[ 0, 0, 1],[ 0, 0, 0],[-1, 0, 0]], 1, 128) # Emboss UR # Canvas = Filter(Canvas, [[ 0, 0,-1],[ 0, 0, 0],[ 1, 0, 0]], 1, 128) # Emboss LL # Canvas = Filter(Canvas, [[ 1, 1, 1],[ 1, 1, 1],[ 1, 1, 1]], 9, 0) # Blur repaint(Canvas) return