Extracts edges from the camera feed using spatial filtering (Sobel filter simulation).
p5.js 2.0
Camera Edge Detection
View Source Code
let video;
let paramInput, paramValue;
let edgeGraphics;
async function setup() {
createCanvas(windowWidth, windowHeight);
pixelDensity(1);
video = await createCapture(VIDEO);
video.size(320, 240);
video.hide();
paramInput = select("#paramInput");
paramValue = select("#paramValue");
}
function draw() {
background(20);
if (
!video ||
!video.elt ||
video.elt.readyState < 2 ||
video.elt.videoWidth === 0
) {
fill(255);
textAlign(CENTER, CENTER);
textSize(24);
text("Loading camera...", width / 2, height / 2);
return;
}
let vW = video.width || video.elt.videoWidth;
let vH = video.height || video.elt.videoHeight;
if (!edgeGraphics || edgeGraphics.width !== vW) {
edgeGraphics = createGraphics(vW, vH);
}
let threshold = 50;
if (paramInput) {
threshold = int(paramInput.value());
if (paramValue) paramValue.html(threshold);
}
let img = video.get();
img.loadPixels();
if (img.pixels && img.pixels.length > 0) {
let w = img.width;
let h = img.height;
edgeGraphics.loadPixels();
if (edgeGraphics.pixels) {
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
let idx = (y * w + x) * 4;
let idxR = (y * w + (x + 1)) * 4;
let idxB = ((y + 1) * w + x) * 4;
let b = img.pixels[idx];
let bR = img.pixels[idxR];
let bB = img.pixels[idxB];
let diff = abs(b - bR) + abs(b - bB);
let outIdx = (y * w + x) * 4;
if (diff > threshold) {
edgeGraphics.pixels[outIdx] = 0;
edgeGraphics.pixels[outIdx + 1] = 255;
edgeGraphics.pixels[outIdx + 2] = 100;
edgeGraphics.pixels[outIdx + 3] = 255;
} else {
edgeGraphics.pixels[outIdx] = 0;
edgeGraphics.pixels[outIdx + 1] = 0;
edgeGraphics.pixels[outIdx + 2] = 0;
edgeGraphics.pixels[outIdx + 3] = 255;
}
}
}
edgeGraphics.updatePixels();
}
let aspect = w / h;
let drawW = height * aspect;
let drawH = height;
if (drawW > width) {
drawW = width;
drawH = width / aspect;
}
let drawX = (width - drawW) / 2;
let drawY = (height - drawH) / 2;
push();
translate(width, 0);
scale(-1, 1);
let invDrawX = width - (drawX + drawW);
tint(255, 60);
image(img, invDrawX, drawY, drawW, drawH);
noTint();
image(edgeGraphics, invDrawX, drawY, drawW, drawH);
pop();
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}