# erodedilate.py
from Processing import *

# Compute luminance with model used for HDTV
def luminance( c ):
    return 0.2126 * red(c) + 0.7152 * green(c) + 0.0722 * blue(c)

# Perform erosion on img1 and save to img2
def erode(img1, img2):
    # Load pixels and get dimensions
    img1.loadPixels()
    img2.loadPixels()
    w = img1.width()
    h = img1.height()

    # Loop over all pixels
    for r in range( 1, h-1 ):
        for c in range( 1, w-1 ):

            # Init min luminance and color
            minlum = 255
            minclr = color(255)

            # Loop over analysis region
            for i in range(3):
                for j in range(3):
                    # Compute indexes of adjacent pixels
                    cc = c + j - 1
                    rr = r + i - 1

                    # Update if luminance is lower
                    clr = img1.getPixel(cc, rr)
                    lum = luminance( clr )
                    if lum < minlum:
                        minlum = lum
                        minclr = clr

            # Set minimum color in img2
            img2.setPixel(c, r, minclr)

    # Copy modified pixels from buffer to image
    img2.updatePixels()

# Perform dilation on img1 and save to img2
def dilate(img1, img2):
    # Load pixels and get dimensions
    img1.loadPixels()
    img2.loadPixels()
    w = img1.width()
    h = img1.height()

    # Loop over all pixels
    for r in range( 1, h-1):
        for c in range( 1, w-1):

            # Init max luminance and color
            maxlum = 0
            maxclr = color(0)

            # Loop over analysis region
            for i in range(3):
                for j in range(3):
                    # Compute indexes of adjacent pixels
                    cc = c + j - 1
                    rr = r + i - 1

                    # Update if luminance is lower
                    clr = img1.getPixel(cc, rr)
                    lum = luminance( clr )
                    if lum > maxlum:
                        maxlum = lum
                        maxclr = clr

            # Set maximum color in img2
            img2.setPixel(c, r, maxclr)

    # Copy modified pixels from buffer to image
    img2.updatePixels()

# Load image three times and open a window
img1 = loadImage("andy-warhol2.jpg")
img2 = loadImage("andy-warhol2.jpg")
img3 = loadImage("andy-warhol2.jpg")
w = img1.width()
h = img1.height()

window( w, h )
keepAbove(True)

image( img1,0,0 )       # Draw the first image on the window

print("Eroding...")
erode( img1, img2 )     # Erode image
image( img2,0,0 )       # Draw eroded image

print("Dilating...")
dilate( img2, img3 )    # Dilate image
image( img3,0,0 )       # Draw dilated image

print("Done")
