The Creative Coder’s Field Guide

Everything You Need to Survive and Thrive with p5.js

Creative Coding · Week 9

Pixel-PusherImages, webcam video and the pixels array in p5.js

Every photo and every webcam frame is a grid of tiny colored squares, and every square is just four numbers. This week you load images and live video into a sketch, read the color of any pixel, and rewrite those numbers to pixelate, invert, blur, and remix what the camera sees.

Images + video + pixels · editor.p5js.org + a webcam · Understand → Know → Do
01The idea

An image is a grid of numbers

Zoom far enough into any photo on your screen and it stops being a picture. It becomes a grid of tiny colored squares called pixels, and every one of those squares is stored as a handful of numbers.

You already know those numbers. In Week 1 you mixed colors with fill(210, 30, 92): a red amount, a green amount, a blue amount, each from 0 to 255. A pixel is exactly that, plus a fourth number for alpha (how opaque it is). A 400×400 image is 160,000 of those little color recipes, lined up in rows.

a zoomed-in corner of an image one pixel R210red G30green B92blue A255alpha (opacity) four numbers, each 0–255
Every pixel is the same color recipe you have been passing to fill() since Week 1. This week you learn to read those recipes out of an image, and to write new ones back in.

That one idea opens up the whole week. If an image is numbers, then you can load one and draw it, read the color at any spot, and change the numbers to make something new. A live webcam feed is the same thing again: a fresh grid of numbers, many times a second.

02Inspiration

Artists who worked in pixels first

Building pictures out of small, separate units is much older than computers. A few artists worth looking up before you start:

  • Julius Nelson, Artyping (1939): portraits and scenes made entirely from typewriter characters. Each letter is a “pixel” whose darkness depends on how much ink it puts down. It is the ancestor of ASCII art.
  • Chuck Close, Phil: huge portraits painted from a grid. Up close you see cells of color; step back and a face appears.
  • Thomas Bayrle: images built from hundreds of tiny repeated images, so the small pictures become the “pixels” of a big one.
  • Jim Campbell, Ambiguous Icon #5 (Running, Falling) (2000): moving figures shown on a very low-resolution grid of LEDs. With so few pixels, your brain fills in the rest.
A large black-and-white portrait of a man with curly hair, built from a grid of small marks, hanging in a gallery.
Phil (1976), Chuck Close. Louisiana Museum of Modern Art
A framed portrait of a blonde woman with red lips, made from hundreds of small repeated images, hung on a wall that is itself patterned with tiny images.
Thomas Bayrle, Playtime Exhibit, New Inc Museum August 2018
A gallery room whose walls and floor are covered in tiny repeated images, with two large pictures on the walls built the same way.
Thomas Bayrle, Playtime Exhibit, New Inc Museum August 2018
A wall-mounted grid of small white LEDs, seen at an angle, showing a blurry figure in motion.
Ambiguous Icon # 5 (Running, Falling), 2000 Jim Campbell

Photos by David Stein.

And for live video:

  • Nam June Paik pulled and distorted television images (sometimes with magnets held against the screen) and built sculptures out of stacks of TVs. He is often called the father of video art.
  • Slit-scan: build one image out of thin strips taken at different moments. John Whitney, a pioneer of computer animation (see his film Catalog), developed the technique, and Douglas Trumbull used it for the “Stargate” sequence in 2001: A Space Odyssey. In section 05 you’ll do a version of it with a webcam.
03Loading images

Getting a picture into your sketch

An image file has to be part of your sketch before p5 can load it. In the p5 web editor:

  1. Click the > arrow above your code to open the file list.
  2. Click + and choose Upload file.
  3. Drag your .png or .jpg into the upload window. It now sits next to sketch.js.

Then load it with loadImage(), using the file’s exact name:

sketch.js

let img1;

async function setup() {
  createCanvas(400, 400);
  img1 = await loadImage("sunset400.png");
}

function draw() {
  background(220);
  image(img1, 0, 0, width, height);
}

Two new words. Loading a file takes time, so loadImage() doesn’t hand back the image right away. await means wait here until the image has finished loading. A function is only allowed to wait if it is marked async, so setup() becomes async function setup(). Because of that wait, draw() never runs before img1 exists.

Old tutorials use preload(). Before p5 2.0, images were loaded in a special preload() function that ran before setup(), with no await. You will see this in older videos and examples. It does the same job, but it doesn’t work in p5 2.x, so use the async/await version above.

// p5 1.x only: don't write new code this way
function preload() {
  img1 = loadImage("sunset400.png");
}

Spelling counts. "Sunset400.PNG" and "sunset400.png" are different files to a web server. If your image doesn’t appear, check the console and compare the name character by character.

04Drawing images

Placing, sizing, and resizing

image() works like rect(): you give it a position, and optionally a width and height. Leave the size off and the image is drawn at its own size.

CodeWhat it does
image(img, x, y)draws the image at its own size, top-left corner at (x, y)
image(img, x, y, w, h)stretches or shrinks it to w × h as it is drawn
img.width, img.heightthe image’s size in pixels
img.resize(w, h)permanently changes the image’s size; its pixels are rebuilt at the new size

An image is a value like any other, so it can go anywhere a value can: drawn twice, drawn inside a loop, or stored in an array. And since image() uses the same coordinate system as everything else, translate(), rotate(), and push()/pop() from Week 5 all work on it.

Resize before you read pixels. Later this week you will match image pixels to canvas pixels one for one. That only lines up if the image and the canvas are the same size, which is why you will often see img.resize(width, height) right after loading.

05Live video

Your webcam is an image that keeps changing

createCapture(VIDEO) turns on the computer’s camera (your browser will ask permission the first time) and gives you back a video object. You can pass that object to image() exactly like a loaded picture. Every time draw() runs, it shows the newest frame.

sketch.js

let video;

function setup() {
  createCanvas(400, 300);
  video = createCapture(VIDEO);
  video.size(400, 300);   // ask for a 400 x 300 feed
  video.hide();           // hide the extra video element p5 adds below the canvas
}

function draw() {
  background(220);
  image(video, 0, 0, width, height);
}
  • video.hide(): p5 shows the raw camera feed as its own element on the page. You almost always want to hide it and draw the video yourself on the canvas, where you control it.
  • video.size(w, h) sets the capture resolution. Smaller is faster to process, which matters once you start reading pixels every frame.

Playing with frames

Once video is “just an image,” everything from section 04 applies. Some example sketches to open and pull apart:

Saving a frame. video.get() with no arguments returns a copy of the current frame as an ordinary image. Push those copies into an array (Week 6) and you have a flip-book of the last few seconds, which is how the 8-frame TV sketch works.

06Reading a pixel

Asking an image for one color: get()

The easiest way to read a pixel is get(x, y). It returns that pixel’s color as an array of four numbers, [r, g, b, a], which fill() accepts directly.

let myPic;

async function setup() {
  createCanvas(400, 400);
  myPic = await loadImage("purpleFlower.png");
  myPic.resize(400, 400);   // match the canvas, so image x/y = canvas x/y
  noStroke();
}

function draw() {
  background(0);
  // sample every 20th pixel and draw a dot in its color
  for (let x = 0; x < width; x += 20) {
    for (let y = 0; y < height; y += 20) {
      let c = myPic.get(x, y);
      fill(c);
      circle(x + 10, y + 10, 18);
    }
  }
}

That nested loop is the same grid pattern from Week 4. The difference is that each cell now asks the image what color to be. Change the step from 20 to 10 or 5 and watch the picture sharpen.

Example sketches built on get():

get() is easy but slow. Each call does a lot of work behind the scenes to hand you one color. A few hundred calls a frame is fine. Tens of thousands a frame (say, every pixel of a webcam) will drag your sketch down. For that, use the pixels array (next section).

07The pixels array

Every pixel in one long list

Behind the scenes, an image keeps all its numbers in a single array called pixels. It isn’t a grid; it’s one long line. The first four numbers are the top-left pixel’s red, green, blue, and alpha. The next four are the pixel to its right, and so on across the first row, then the second row, all the way down.

Here is a tiny image, just 4 pixels wide and 4 tall. Number its pixels left to right, top to bottom, and you get exactly the order they are stored in:

the image: 4 × 4 pixels x 0 x 1 x 2 x 3 y 0 y 1 y 2 y 3 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Number the pixels left to right, top to bottom: that is their order in the array. pixel (2, 1) is number 2 + 1 × 4 = 6 pixel number = x + y × width the same pixels, as one long list 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 row y = 0 row y = 1 row y = 2 row y = 3
Row 0 comes first, then row 1 picks up right where it ended, and so on. That is why a pixel’s place in the list is x + y * width: skip y whole rows, then move x more.

Each entry in that list is really four numbers, so zoom in on the start of the array and it looks like this:

rgba rgba rgba 0123 4567 891011 pixel 0 · (0, 0) pixel 1 · (1, 0) pixel 2 · (2, 0) … index = 4 * (x + y * width) index is where that pixel’s red lives; green, blue, alpha follow at +1, +2, +3
The small numbers above the boxes are array indexes. Every pixel takes up four slots, so pixel n starts at index 4 * n.

Finding a pixel’s index

To jump straight to the pixel at (x, y), count how many pixels come before it: y full rows of width pixels, plus x more in its own row. Multiply by 4 because each pixel takes four slots:

let index = 4 * (x + y * width);
let r = pixels[index];
let g = pixels[index + 1];
let b = pixels[index + 2];
let a = pixels[index + 3];

If you just want to visit every pixel in order, you don’t need the formula. Step through the array four at a time:

for (let i = 0; i < pixels.length; i += 4) {
  // pixels[i] is red, i+1 green, i+2 blue, i+3 alpha
}

The load / change / update rule

The pixels array is a copy you work on, not the live image. Every time you use it, follow the same three steps:

loadPixels()
copy the current pixels into the pixels array so you can read them
pixels[ ]
read or change the numbers, as many as you like
updatePixels()
copy your changes back so they actually show up. Forget this and nothing changes.

On an image you call them on the image: myImage.loadPixels(), myImage.pixels, myImage.updatePixels(). With no object in front, they work on the canvas itself.

Use pixelDensity(1) when you touch canvas pixels. Retina and other high-resolution screens draw each canvas pixel with 2×2 (or more) real pixels, so the canvas’s pixels array is four times longer than width * height * 4 and the index formula stops lining up. Calling pixelDensity(1) in setup() makes one canvas pixel equal one array pixel. Images and video don’t need this.

08Changing pixels

Writing new colors back in

Changing an image

This sketch inverts a photo: every color becomes its opposite (255 minus the old value). It visits every pixel by stepping through the array four at a time:

let img;

async function setup() {
  createCanvas(400, 400);
  img = await loadImage("sunset400.png");
  img.resize(400, 400);

  img.loadPixels();
  for (let i = 0; i < img.pixels.length; i += 4) {
    img.pixels[i]     = 255 - img.pixels[i];       // red
    img.pixels[i + 1] = 255 - img.pixels[i + 1];   // green
    img.pixels[i + 2] = 255 - img.pixels[i + 2];   // blue
    // img.pixels[i + 3] is alpha: leave it alone
  }
  img.updatePixels();
}

function draw() {
  image(img, 0, 0);
}

Because the change happens once in setup(), the image is changed for good; draw() just shows the result. Try other rules inside the loop: keep only the red (g and b set to 0), swap red and blue, or make a pixel white only if it was bright to begin with.

Loop over all of it. An easy mistake is a loop that only changes the first 1000 array entries. It works, but 1000 entries is only 250 pixels of a 160,000-pixel image (a thin line along the top edge), so it looks like nothing happened. Using img.pixels.length as the loop limit guarantees you cover everything.

Changing the canvas

The canvas has a pixels array too. This sketch sprinkles 1000 random-colored pixels every frame, using the index formula to place each one:

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);   // one canvas pixel = 4 array slots
  background(220);
}

function draw() {
  loadPixels();
  for (let n = 0; n < 1000; n++) {
    // random() gives decimals like 37.42, but array indexes must be
    // whole numbers, so floor() rounds down
    let x = floor(random(width));
    let y = floor(random(height));
    let index = 4 * (x + y * width);
    pixels[index]     = random(255);   // red
    pixels[index + 1] = random(255);   // green
    pixels[index + 2] = random(255);   // blue
    pixels[index + 3] = 255;           // alpha: fully opaque
  }
  updatePixels();
}
09Pixelating video

Turning the webcam into big blocks

Put sections 05 to 08 together: read the live video’s color every few pixels, and draw a big square of that color. The result is a chunky, low-resolution mirror, a lot like a Jim Campbell piece.

The easy way, with get()

for (let x = 0; x < width; x += cellSize) {
  for (let y = 0; y < height; y += cellSize) {
    let c = video.get(x, y);
    fill(c);
    rect(x, y, cellSize, cellSize);
  }
}

The fast way, with the pixels array

Same picture, but it reads the video’s pixels array directly. With small cells (many reads per frame) this one stays smooth where the get() version starts to stutter.

sketch.js

let video;
let cellSize = 20;

function setup() {
  createCanvas(400, 300);
  video = createCapture(VIDEO);
  video.size(400, 300);   // same size as the canvas
  video.hide();
  noStroke();
}

function draw() {
  video.loadPixels();
  if (video.pixels.length === 0) return;   // camera not ready yet

  for (let x = 0; x < video.width; x += cellSize) {
    for (let y = 0; y < video.height; y += cellSize) {
      let index = 4 * (x + y * video.width);
      fill(video.pixels[index], video.pixels[index + 1], video.pixels[index + 2]);
      rect(x, y, cellSize, cellSize);
    }
  }
}

Notice the formula uses video.width, not the canvas’s width. Always use the width of whatever you’re reading from. Here they happen to match, but if you later change the video size, the sketch keeps working.

10Off-screen canvases

Drawing somewhere nobody can see: createGraphics()

createGraphics(w, h) makes a second, invisible canvas. You draw on it with the usual commands, written with its name in front (g1.background(), g1.rect(), g1.image()), and then you can place the whole thing on the main canvas with image(), just like a picture.

let g1;

function setup() {
  createCanvas(400, 400);
  g1 = createGraphics(400, 400);
  g1.rect(100, 200, 200, 50);   // drawn on g1, not on the canvas
}

function draw() {
  background(220);
  image(g1, 0, 0);              // now g1 appears
}

Why bother? A few reasons you will run into:

  • Layers. Draw a slow-building trail on a graphics layer that never gets cleared, while the main canvas redraws a moving character over it every frame.
  • Scratch space. Keep an untouched copy of an image to read from while you change the canvas (the blur filter in the next section needs exactly this).
  • Reuse. Draw something complicated once, then stamp it with image() as many times as you like.

A graphics object also has its own loadPixels(), pixels, and updatePixels(), so everything in sections 07 and 08 works on it.

11Filters

Extra: blur and edge detection by hand

Photo apps’ blur and “find edges” filters are just the pixel loops you already know, with a bit of arithmetic. This section is optional, but it is a satisfying way to see what those buttons actually do.

Blur: become the average of your neighbors

To blur, replace each pixel with the average of the pixels around it. Sharp jumps in color get smoothed out, so the image goes soft. The pattern of which neighbors count (and how much) is called a kernel. Here is the simplest one: the eight neighbors all count equally, and the center pixel is left out.

111 1X1 111 the kernel, centered on one pixel add the 8 neighbors divide by 8 = the new value for X repeat for red, green, and blue, then for every pixel in the image
Sliding a kernel across every pixel and combining the neighbors is called convolution. Change the numbers in the kernel and you get a different filter: sharpen, emboss, or a smoother “Gaussian” blur.

One catch: you have to read from an untouched copy. If you blur pixels in place, each pixel would be averaged with neighbors you’ve already blurred, and the result smears. So the code reads from img and writes into a fresh, empty image made with createImage():

// where pixel (x, y) starts in an image that is w pixels wide
function ndx(x, y, w) {
  return 4 * (x + y * w);
}

function blurImage(img) {
  let w = img.width;
  let h = img.height;
  let out = createImage(w, h);   // blank image, same size
  img.loadPixels();
  out.loadPixels();

  // skip the outer border: edge pixels don't have 8 neighbors
  for (let x = 1; x < w - 1; x++) {
    for (let y = 1; y < h - 1; y++) {
      for (let c = 0; c < 3; c++) {          // 0 = red, 1 = green, 2 = blue
        let sum = 0;
        for (let dx = -1; dx <= 1; dx++) {
          for (let dy = -1; dy <= 1; dy++) {
            if (dx === 0 && dy === 0) continue;   // skip the center
            sum += img.pixels[ndx(x + dx, y + dy, w) + c];
          }
        }
        out.pixels[ndx(x, y, w) + c] = sum / 8;
      }
      out.pixels[ndx(x, y, w) + 3] = 255;   // opaque
    }
  }
  out.updatePixels();
  return out;
}

Call it after loading, like img = blurImage(img). Run it a few times in a row for a stronger blur. This example sketch does the same thing on the canvas, using a createGraphics() layer as the untouched copy:

Edges: look for big jumps

An edge in a photo is a place where brightness changes suddenly, like a dark coat against a white wall. To find edges, compare each pixel’s brightness to its neighbor’s. Take this row of brightness values (0 is black, 255 is white):

10   15   20   150   155   160   30   35   40

Most neighbors differ by about 5. Between 20 and 150, and between 160 and 30, the jump is huge: those are edges. So: if the difference is bigger than some threshold (say 50), paint that pixel white; otherwise, black.

// inside a loop over x and y, reading from img, writing to out
let i = ndx(x, y, w);
let j = ndx(x + 1, y, w);   // the neighbor to the right
let b1 = (img.pixels[i] + img.pixels[i + 1] + img.pixels[i + 2]) / 3;
let b2 = (img.pixels[j] + img.pixels[j + 1] + img.pixels[j + 2]) / 3;
let v = abs(b1 - b2) > 50 ? 255 : 0;
out.pixels[i] = v;
out.pixels[i + 1] = v;
out.pixels[i + 2] = v;
out.pixels[i + 3] = 255;

Want to go further? Wikipedia’s Kernel (image processing) page lists ready-made kernels to try, and Gaussian blur explains the smoother blur most photo apps use.

12Reference

Quick reference

Images and video

CodeWhat it does
img = await loadImage("f.png")load an image file (inside async function setup())
image(img, x, y, w, h)draw an image, video, or graphics layer; w, h optional
img.width, img.heightsize in pixels
img.resize(w, h)permanently resize an image
video = createCapture(VIDEO)start the webcam
video.size(w, h)set the capture resolution
video.hide()hide the extra video element on the page
video.get()copy the current frame as an image
g = createGraphics(w, h)an off-screen canvas; draw with g.rect() etc.
createImage(w, h)a blank image to fill with pixels

Pixels

CodeWhat it does
img.get(x, y)one pixel’s color as [r, g, b, a] (easy, slow)
loadPixels()fill the pixels array (before reading or writing)
pixels[i]red of a pixel; i+1 green, i+2 blue, i+3 alpha
4 * (x + y * w)array index where pixel (x, y) starts, in something w pixels wide
updatePixels()write your changes back (after changing)
pixelDensity(1)make canvas pixels line up with the array (call in setup())

Put img., video., or g. in front of loadPixels, pixels, and updatePixels to work on that object; leave it off to work on the canvas.

13Practice

Be able to do

Find a pixel by hand

An image is 10 pixels wide. Using the formula from section 07, at what index does the red value of pixel (3, 2) live? What about its blue value?

Red at 4 × (3 + 2 × 10) = 92. Blue is two slots later, at 94.

Load and arrange

Upload two images of your own. Draw one filling the canvas and the other as a small “picture-in-picture” in a corner. Then use a loop to draw the small one five times across the bottom (section 04).

Dots from a photo

Starting from the get() sketch in section 06, make the circle size depend on the pixel’s brightness as well as its color. Hint: the average of c[0], c[1], and c[2] is a decent brightness (0–255), and brightness / 255 * 18 turns it into a diameter from 0 to 18.

Your own color filter

Using the invert sketch from section 08 as a starting point, write a filter that turns a photo grayscale: set red, green, and blue all to that pixel’s average. Then add a second rule of your own choosing (only the bright pixels turn pink, say).

Mirror, mirror

Webcam images feel backwards because they aren’t mirrored. Make the pixelated video from section 09 behave like a mirror. Hint: draw the square for column x at width - x - cellSize instead of x.

A time-delay booth

Every 10 frames, save video.get() into an array (Week 6), keeping only the 8 most recent frames. Draw all 8 in a row along the bottom of the canvas, oldest first, so you can watch yourself move across time (section 05).