xxxxxxxxxx
68
// https://kylemcdonald.github.io/cv-examples/
var capture;
var previousPixels;
var flow;
var w = 1920,
h = 1080;
var step = 4;
function setup() {
createCanvas(w, h);
capture = createCapture({
audio: false,
video: {
width: w,
height: h
}
}, function() {
console.log('capture ready.')
});
capture.elt.setAttribute('playsinline', '');
capture.hide();
flow = new FlowCalculator(step);
}
function copyImage(src, dst) {
var n = src.length;
if (!dst || dst.length != n) dst = new src.constructor(n);
while (n--) dst[n] = src[n];
return dst;
}
function same(a1, a2, stride, n) {
for (var i = 0; i < n; i += stride) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}
function draw() {
capture.loadPixels();
if (capture.pixels.length > 0) {
if (previousPixels) {
// cheap way to ignore duplicate frames
if (same(previousPixels, capture.pixels, 4, width)) {
return;
}
flow.calculate(previousPixels, capture.pixels, capture.width, capture.height);
}
previousPixels = copyImage(capture.pixels, previousPixels);
if (flow.flow && flow.flow.u != 0 && flow.flow.v != 0) {
strokeWeight(2);
flow.flow.zones.forEach(function(zone) {
stroke(map(zone.u, -step, +step, 0, 255),
map(zone.v, -step, +step, 0, 255), 128);
line(zone.x, zone.y, zone.x + zone.u, zone.y + zone.v);
})
}
noFill();
stroke(255);
}
}