• WORK
  • ABOUT
  • LABS
  • BLOG
Menu

WAWA LABS

  • WORK
  • ABOUT
  • LABS
  • BLOG
Screen Shot 2020-09-17 at 12.00.32 PM.png

Motion Detect Art

September 13, 2020

This code might not work on this website because you need a webcam permission.

You can try on P5 editor. (There is a link to p5 editor on the right)

P5 editor

let myVideo;
let pastPixels = [];
let threshSlider

function setup() {
  createCanvas(640, 480);
  myVideo = createCapture(VIDEO);
  myVideo.size(width, height);
  myVideo.hide();

  threshSlider = createSlider(0, 255, 40);
  
  
}


function draw() {
  myVideo.loadPixels();

  const currentPixels = myVideo.pixels;
  let threshValue = threshSlider.value();


  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const i = (y * width + x) * 4

      const rDiff = abs(currentPixels[i + 0] - pastPixels[i + 0]);
      const gDiff = abs(currentPixels[i + 1] - pastPixels[i + 1]);
      const bDiff = abs(currentPixels[i + 2] - pastPixels[i + 2]);


      // set past pixels to current pixels
      pastPixels[i + 0] = currentPixels[i + 0];
      pastPixels[i + 1] = currentPixels[i + 1];
      pastPixels[i + 2] = currentPixels[i + 2];
      pastPixels[i + 3] = currentPixels[i + 3];

      avgDiff = (rDiff + gDiff + bDiff) / 3;

      if (avgDiff < threshValue) {
        currentPixels[i + 0] = random(255);
        currentPixels[i + 1] = random(255);
        currentPixels[i + 2] = random(255);
        currentPixels[i + 3] = 30;
      } else {
        currentPixels[i + 0] = 0
        currentPixels[i + 1] = 0
        currentPixels[i + 2] = 0
        currentPixels[i + 3] = 255;
      }
    }
  }

  myVideo.updatePixels();
  image(myVideo, 0, 0, width, height);
}
← API & WebRTCPhysarum Polycephalum Pt.2 →

© 2021 All Rights Reserved