# grayscale.py
# Convert color image to grayscale

from Processing import *

# Load the image to process
img = loadImage("kodim01.png")

# Create a window of the same size
w = int( img.width() )
h = int( img.height() )
window( w, h )

image( img, 0, 0)       # Draw the image

# Compute the "lightness" of a color
def lightness( c ):
    r = red(c)
    g = green(c)
    b = blue(c)
    return 0.5*(max(r, g, b) + min(r, g, b))

# Compute average of three color components
def average( c ):
    return (red(c) + green(c) + blue(c))/3.0

# Compute luminance with model used for HDTV
def luminance( c ):
    return 0.2126 * red(c) + 0.7152 * green(c) + 0.0722 * blue(c)

# Perform the grayscale conversion
def grayscale(o, e):
    image( img, 0, 0)               # Redraw the original image

    loadPixels()                    # Load pixels in preparation for processing

    for i in range(w):              # Loop over all pixels
        for j in range(h):
            c = getPixel(i, j)      # Get the color

            #gray = lightness(c)     # Convert using lightness
            #gray = average(c)       # Convert using average
            gray = luminance(c)     # Convert using luminance

            setPixel(i, j, color(gray))

    updatePixels()                  # Update pixels in image

# When the mouse is pressed, perform the conversion
onMousePressed += grayscale

