# histogram.py
from Processing import *
window(516, 516)

# Lists to hold histogram values
aa = [0 for i in range(256)]  # Count up shades of gray (all)
ra = [0 for i in range(256)]  # Count up shades of red
ga = [0 for i in range(256)]  # Count up shades of green
ba = [0 for i in range(256)]  # Count up shades of blue

# Load the image to analyze
img = loadImage("kodim02.png")   
img.loadPixels()

# Sum up all pixel values from all colors
for i in range( img.width() ):
    for j in range( img.height() ):
        c = img.getPixel(i, j)
        r = red(c)
        g = green(c)
        b = blue(c)
    
        # Increment histogram item amounts
        ra[ r ] += 1
        ga[ g ] += 1
        ba[ b ] += 1
        aa[ int((r+g+b)/3.0) ] += 1

# Find max value
max = 0.0
for i in range(256):
    if ra[i] > max: max = ra[i]
    if ga[i] > max: max = ga[i]
    if ba[i] > max: max = ba[i]
    if aa[i] > max: max = aa[i]

# Draw scaled histogram
background(255)
noFill()

# Borders
stroke(0)
rect(0, 0, 256, 256)
stroke(255,0,0)
rect(257, 0, 256, 256)
stroke(0,255,0)
rect(0, 257, 256, 256)
stroke(0,0,255)
rect(257, 257, 256, 256)

# Lines
for i in range(256):
    # all
    stroke(0)
    h = map(aa[i], 0, max, 0, 255)
    line(i, 255, i, 255-h)
    
    # red
    stroke(255,0,0)
    h = map(ra[i], 0, max, 0, 255)
    line(257+i, 255, 257+i, 255-h)
    
    # green
    stroke(0,255,0)
    h = map(ga[i], 0, max, 0, 255)
    line(i+1, 514, i+1, 514-h)
    
    # blue
    stroke(0,0,255)
    h = map(ba[i], 0, max, 0, 255)
    line(257+i, 514, 257+i, 514-h)
