The Creative Coder’s Field Guide
Everything You Need to Survive and Thrive with p5.js
Creative Coding · Week 9
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.
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.
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.
Building pictures out of small, separate units is much older than computers. A few artists worth looking up before you start:
Photos by David Stein.
And for live video:
An image file has to be part of your sketch before p5 can load it. In the p5 web editor:
.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.
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.
| Code | What 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.height | the 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.
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.Once video is “just an image,” everything from section 04 applies. Some example sketches to open and pull apart:
Run: random strips of video (a slit-scan feel)
Run: the live feed inside a TV
Run: an array of video captures
Run: grab 8 frames and animate them in a TV
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.
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():
Run: drawing with pixel colors
Run: pixel example 2 Pixels are shown as letters X and O
Run: pixel example 3 Pixels are shown as letters X and O
Run: pixel example 4 Pixels are shown as circles with varying diameters
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).
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:
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:
4 * n.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 pixels array is a copy you work on, not the live image. Every time you use it, follow the same three steps:
pixels array so you can read themOn 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.
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.
Run: changing the pixels of an image
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.
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();
}
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.
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);
}
}
Run: pixelated video with get()
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.
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:
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.
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.
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.
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:
Run: a blur filter on the canvas
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.
| Code | What 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.height | size 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 |
| Code | What 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.
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.
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).
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.
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).
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.
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).