Skip to content

Latest commit

 

History

History
101 lines (79 loc) · 3.08 KB

2021-11-13-pixel-swapper.md

File metadata and controls

101 lines (79 loc) · 3.08 KB
layout title thumbnail tagline sort-key meta-title meta-description meta-image tags includeP5jsWidget previousPost redirect_from discourseEmbedUrl
post
Pixel Swapper
/tutorials/p5js/images/images/pixel-swapper-1.png
Rearrange the pixels in an image.
1160
Pixel Swapper - p5.js Example
Rearrange the pixels in an image.
/tutorials/p5js/images/images/pixel-swapper-1.png
example
p5.js
javascript
images
false
/tutorials/p5js/images
/examples/p5js/images/pixel-swapper
/examples/p5js/images/pixel-swapper

This sketch rearranges the pixels in an image. Every frame, it chooses a random pixel, and swaps it with another random pixel.


{% include youtube-embed.html slug="-TFPNRH26wU" %}


let img;

function preload() {
  img = loadImage('images/bee.jpg');
}

function setup() {
  createCanvas(400, 400);
  noSmooth();
  img.resize(width, height);
}

function draw() {
  img.loadPixels();
  for (let i = 0; i < 100; i++) {
    swapPixels();
  }
  img.updatePixels();

  image(img, 0, 0, width, height);
}

function averagePixels() {
  const xOne = random(img.width);
  const yOne = random(img.height);
  const colorOne = img.get(xOne, yOne);

  // Uncomment to choose points closer together
  // const xTwo = constrain(xOne + random(-20, 20), 0, img.width-1);
  // const yTwo = constrain(yOne + random(-20, 20), 0, img.height-1);
  const xTwo = random(img.width);
  const yTwo = random(img.height);
  const colorTwo = img.get(xTwo, yTwo);

  const averageColor = color(
    (red(colorOne) + red(colorTwo)) / 2,
    (green(colorOne) + green(colorTwo)) / 2,
    (blue(colorOne) + blue(colorTwo)) / 2
  );

  img.set(xOne, yOne, averageColor);
  img.set(xTwo, yTwo, averageColor);
}

function swapPixels() {
  const xOne = random(img.width);
  const yOne = random(img.height);
  const colorOne = img.get(xOne, yOne);

  // Uncomment to choose points closer together
  // const xTwo = constrain(xOne + random(-20, 20), 0, img.width-1);
  // const yTwo = constrain(yOne + random(-20, 20), 0, img.height-1);
  const xTwo = random(img.width);
  const yTwo = random(img.height);
  const colorTwo = img.get(xTwo, yTwo);

  img.set(xOne, yOne, colorTwo);
  img.set(xTwo, yTwo, colorOne);
}

Edit this code in the p5 editor.

The code contains options for swapping or averaging pixels, either close together or far apart. This creates different kinds of animations:

swapping far away pixels averaging far away pixels swapping close pixels averaging close pixels

Remix Ideas