Camera as sensor (brightness)

See page 289 in Shiffman’s Learning Processing for an explanation of this example.

/**
 * Average Brightness
 */
 
 
import processing.video.*;
 
color black = color(0);
color white = color(255);
int numPixels;
 
Capture video;
 
void setup() {
  size(640, 480); // Change size to 320 x 240 if too slow at 640 x 480
  strokeWeight(5);
 
  // This the default video input, see the GettingStartedCapture 
  // example if it creates an error
  video = new Capture(this, width, height);
 
  // Start capturing the images from the camera
  video.start(); 
 
  numPixels = video.width * video.height;
}
 
void draw() {
  if (video.available()) {
    video.read();
    video.loadPixels();
    float totalBrightness = 0;
    float pixelBrightness; // Declare variable to store a pixel's color
 
    loadPixels();
    //run through every pixel
    for (int i = 0; i < numPixels; i++) {
      //get brightness of each pixel
      pixelBrightness = brightness(video.pixels[i]);
      //add to total
      totalBrightness +=pixelBrightness;
    }
 
    updatePixels();
    println(totalBrightness);
 
    float averageBrightness = totalBrightness/numPixels;
    //set background to averageBrightness.
    background(averageBrightness);
  }
}
'+
1
'+
2 - 3
4 - 5
6 - 7
8 - 9
10 - 11
12 - 13
13 - 14
[x]