Examples / p5.js Examples / / Image Palette

Image Palette

example p5.js javascript images genuary

Click here to view this code in the p5 editor.

Click here to view the result by itself.

let img;
let palette;
let y = 0;

function preload() {
  img = loadImage('images/horizons/horizon-7.jpg');
}

function setup() {
  createCanvas(600, 600);
  img.resize(width, height);

  // Genuary 23 palette
  palette = [
    '#264653', '#2a9d8f',
    '#e9c46a', '#f4a261',
    '#e76f51'
  ];

  image(img, 0, 0);
}

function draw() {
  for (let x = 0; x < width; x++) {
    const imgColor = img.get(x, y);
    const paletteColor = getPaletteColor(imgColor);
    stroke(paletteColor);
    point(x, y);
  }

  y++;
  if (y >= height) {
    noLoop();
  }
}

function getPaletteColor(imgColor) {
  const imgR = red(imgColor);
  const imgG = green(imgColor);
  const imgB = blue(imgColor);

  let minDistance = 999999;
  let targetColor;

  for (const c of palette) {
    const paletteR = red(c);
    const paletteG = green(c);
    const paletteB = blue(c);

    const colorDistance =
      dist(imgR, imgG, imgB,
           paletteR, paletteG, paletteB);

    if (colorDistance < minDistance) {
      targetColor = c;
      minDistance = colorDistance;
    }
  }

  return targetColor;
}

Click here to view this code in the p5 editor.

Click here to view the result by itself.

This sketch replaces the colors in an image with colors from a chosen palette.

I created this for the 23rd day of Genuary which had a prompt of 5 colors: #264653, #2a9d8f, #e9c46a, #f4a261, and #e76f51.

The colors reminded me of a sunset, so I applied the palette filter to a few pictures of horizons I’ve taken recently.

palette image palette image palette image palette image palette image palette image palette image palette image palette image palette image

Remix Ideas

  • Apply this filter to different images.
  • Change the colors in the palette.
  • Instead of going row by row, choose a different random pixel each frame.

Comments and Questions

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!