# threshold.py
# Demonstrating the threshold function

from Processing import *

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

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

# Draw the image
image( img, 0, 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 threshold function
def threshold(o, e):
    image( img, 0, 0)               # Redraw the original image
    cutoff = mouseY()               # Get the cutoff as the y mouse position
    print( "cutoff =", cutoff )

    loadPixels()                    # Load pixels in preparation for processing

    # Loop over all pixels
    for i in range(w):
        for j in range(h):
            c = getPixel(i, j)      # Get the color
                                    # Convert the color to grayscale
            gray = luminance(c)
            if gray >= cutoff:      # Compute threshold:
                gray = 255          # white if above cutoff
            else:
                gray = 0            # black if below cutoff
                                    # Reset color to threshold value
            setPixel(i, j, color(gray))

    updatePixels()                  # Update pixels in image

# When the mouse is pressed, perform the threshold function
onMousePressed += threshold

