9c – Working with Pixels

Background concepts:
for loops, arrays, the PImage datatype, using the video library
Background video tutorials (if you need to backup on these concepts):
for loops:
  variable scope:
A loop inside draw


PART 1 – Images
Review the images section of this site (or chapter or section 15.5 on page 262 of the orange Shiffman book) and consider the PImage data type in the Processing reference.

Processing has two more image functions to access pixels on your screen.
• loadPixels( )—This function is called before you access the pixel array, saying “load the pixels, I would like to speak with them!”
• updatePixels( )—This function is called after you finish with the pixel array, saying “Go ahead and update the pixels, I’m all done!”

These functions allow us to set and talk to each pixel of the screen by loading them into an array called:


Where i is the position along the array. It is like we load the color values of each pixel of the screen into a big long list.

Screen Shot 2015-03-24 at 8.22.29 AM

We an then talk to individual pixels by calculating where they are along this list:

Screen Shot 2015-03-24 at 8.22.43 AM

For example we can set pixel color according to their 2D location:

// Loop through every pixel column
for (int x = 0; x < width; x++) {
  // Loop through every pixel row
  for (int y = 0; y < height; y++){
   // Use the formula to find the 1D location
   int loc = x + y * width;
   if (x % 2 == 0){ // If we are an even column 
     pixels[loc] = color(255);
   }else { // If we are an odd column 
     pixels[loc] = color(0);

Shiffman explains again here.

Make sure you understand the process of ‘loading pixels’ and ‘setting pixels’.

Screen Shot 2015-03-24 at 8.28.09 AM

2 - 3
4 - 5
6 - 7
8 - 9
10 - 11
12 - 13
13 - 14