|
| 1 | +/* |
| 2 | + * @name Histogram |
| 3 | + * @description Calculates the histogram of an image. |
| 4 | + * A histogram is the frequency distribution of the gray levels with the number of |
| 5 | + * pure black values displayed on the left and number of pure white values on the right. |
| 6 | + * Note that this sketch will behave differently on Android, since most images will |
| 7 | + * no longer be full 24-bit color. |
| 8 | + */ |
| 9 | + |
| 10 | +let img; |
| 11 | +let hist = []; |
| 12 | + |
| 13 | +function preload() { |
| 14 | + // Load an image from the data directory |
| 15 | + // Load a different image by modifying the comments |
| 16 | + img = loadImage('assets/frontier.jpg'); |
| 17 | +} |
| 18 | + |
| 19 | +function setup() { |
| 20 | + createCanvas(640, 360); |
| 21 | + image(img, 0, 0); |
| 22 | + |
| 23 | + // Initialize the histogram |
| 24 | + for (let i = 0; i < 256; i++) { |
| 25 | + hist.push(0); |
| 26 | + } |
| 27 | + |
| 28 | + // Calculate the histogram |
| 29 | + for (let i = 0; i < img.width; i++) { |
| 30 | + for (let j = 0; j < img.height; j++) { |
| 31 | + let bright = int(brightness(img.get(i, j))); |
| 32 | + hist[bright]++; |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function draw(){ |
| 38 | + // Find the largest value in the histogram |
| 39 | + let histMax = max(hist); |
| 40 | + stroke(255); |
| 41 | + // Draw half of the histogram (skip every second value) |
| 42 | + for (let i = 0; i < img.width; i += 2) { |
| 43 | + // Map i (from 0..img.width) to a location in the histogram (0..255) |
| 44 | + let which = int(map(i, 0, img.width, 0, 255)); |
| 45 | + // Convert the histogram value to a location between |
| 46 | + // the bottom and the top of the picture |
| 47 | + let y = int(map(hist[which], 0, histMax, img.height, 0)); |
| 48 | + line(i, img.height, i, y); |
| 49 | + } |
| 50 | +} |
0 commit comments