Pixels

In Processing we can access the pixels of an image or those that are displayed on the screen. When accessing them we can pull out the color values and modify it for display.

Here is a quick example that we’ll review:

// Don't forget WRITE_EXTERNAL_STORAGE

PImage theImage;

void setup() {
  //size(400,400);
  theImage = loadImage("dottie.jpg");
}

void draw() {
  loadPixels();
  theImage.loadPixels();

  // Loop through the x
  for (int x = 0; x < theImage.width && x < width; x++ ) {
    // For each x, loop through the y
    for (int y = 0; y < theImage.height && y < height; y++ ) {
      
      // Calculate the array pixel location for the image
      int imageIndex = x + y*theImage.width;
      // Calculate the array pixel location for the screen
      int screenIndex = x + y*width;
      
      // Get the red, green and blue values from image
      float r = red (theImage.pixels[imageIndex]);
      float g = green (theImage.pixels[imageIndex]);
      float b = blue (theImage.pixels[imageIndex]);
      
      // The closer the pixel is to the center, the lower the distance
      float distance = dist(x, y, theImage.width/2, theImage.height/2);

      float maxDistance = sqrt(sq(theImage.width) + sq(theImage.height));
        
      float distanceRatio = distance/maxDistance;

      // We want closer pixels to be brighter
      r = r*(1-distanceRatio);
      g = g*(1-distanceRatio);
      b = b*(1-distanceRatio);

      // We also want sepia
      r = r + 99;
      g = g + 66;
      b = b + 33;

      // Constrain RGB to between 0-255
      r = constrain(r, 0, 255);
      g = constrain(g, 0, 255);
      b = constrain(b, 0, 255);
        
      // Make a new color out of the new RGB values and set the pixels of the sketch
      color c = color(r, g, b);
      pixels[screenIndex] = c;
    }
  }

  // Call updatePixels to tell processing to draw the pixel values to the screen
  updatePixels();
  
  filter(BLUR, 2);
}

void mousePressed() {
 // Save output to the SD card
 save(android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/output.tif"); 
}

Checkout the filter and blend references as well.