speedy-vision
Version:
GPU-accelerated Computer Vision for JavaScript
349 lines (300 loc) • 11.9 kB
HTML
<!--
speedy-vision.js
GPU-accelerated Computer Vision for JavaScript
Copyright 2020-2022 Alexandre Martins <alemartf(at)gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
optical-flow.html
Feature tracking demo
-->
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="speedy-vision.js: GPU-accelerated Computer Vision for JavaScript">
<meta name="author" content="Alexandre Martins">
<title>Optical flow - feature tracking</title>
<script src="../dist/speedy-vision.js"></script>
<link href="style.css" rel="stylesheet">
</head>
<body>
<h1>LK optical flow</h1>
<p><em>Click on a <strong>moving region</strong> of the video to track it!</em></p>
<form autocomplete="off">
<div>
<label for="window-size">Window size</label>
<select id="window-size">
<option value="5">5x5</option>
<option value="7">7x7</option>
<option value="9">9x9</option>
<option value="11" selected>11x11</option>
<option value="13">13x13</option>
<option value="15">15x15</option>
<option value="21">21x21</option>
</select>
<label for="levels">Pyramid levels</label>
<select id="levels">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<label for="discard-threshold">Discard threshold</label>
<select id="discard-threshold">
<option value="0.0">0.0</option>
<option value="0.0001" selected>0.0001</option>
<option value="0.001">0.001</option>
<option value="0.01">0.01</option>
</select>
</div>
<div class="separator"></div>
<div>
<label for="number-of-iterations">Max. iterations</label>
<select id="number-of-iterations">
<option value="3">3</option>
<option value="5">5</option>
<option value="8">8</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="30" selected>30</option>
</select>
<label for="epsilon">Epsilon for early termination</label>
<select id="epsilon">
<option value="0">0</option>
<option value="0.01" selected>0.01</option>
<option value="0.03">0.03</option>
</select>
<span>
<a href="javascript:reset()">Reset values</a>
</span>
</div>
<div class="separator"></div>
<div>
<label for="speed-slider">Video speed</label>
<input type="range" id="speed-slider" min="0.10" max="2" value="1" step="0.01">
</div>
</form>
<div>
<span id="status"></span>
<canvas id="canvas-demo" style="cursor:pointer"></canvas>
</div>
<div>
<button id="play">Play / pause</button>
<button id="detect">Detect features</button>
<button id="clear">Clear features</button>
</div>
<video
src="../assets/people.webm"
poster="../assets/loading.jpg"
width="640" height="360"
preload="auto"
muted hidden
title="Free to use video by Free Videos, https://www.pexels.com/pt-br/foto/853889/">
</video>
<script>
let userPoints = [];
window.onload = async function()
{
// get DOM elements
const windowSize = document.getElementById('window-size');
const discardThreshold = document.getElementById('discard-threshold');
const levels = document.getElementById('levels');
const numberOfIterations = document.getElementById('number-of-iterations');
const epsilon = document.getElementById('epsilon');
// load the video
const video = document.querySelector('video');
const media = await Speedy.load(video);
video.play();
// create the pipeline
const pipeline = Speedy.Pipeline();
const imgsrc = Speedy.Image.Source();
const kpsrc = Speedy.Keypoint.Source();
const grey = Speedy.Filter.Greyscale();
const pyr = Speedy.Image.Pyramid();
const harris = Speedy.Keypoint.Detector.Harris();
const clipper = Speedy.Keypoint.Clipper();
const buf = Speedy.Image.Buffer();
const bufpyr = Speedy.Image.Pyramid();
const lk = Speedy.Keypoint.Tracker.LK();
const mixer = Speedy.Keypoint.Mixer();
const sink = Speedy.Keypoint.SinkOfTrackedKeypoints();
imgsrc.media = media;
harris.quality = 0.10;
harris.capacity = 0;
imgsrc.output().connectTo(grey.input());
grey.output().connectTo(pyr.input());
grey.output().connectTo(buf.input());
buf.output().connectTo(bufpyr.input());
bufpyr.output().connectTo(harris.input());
harris.output().connectTo(clipper.input());
clipper.output().connectTo(mixer.input('in1'));
kpsrc.output().connectTo(mixer.input('in0'));
bufpyr.output().connectTo(lk.input('previousImage'));
pyr.output().connectTo(lk.input('nextImage'));
mixer.output().connectTo(lk.input('previousKeypoints'));
lk.output().connectTo(sink.input());
lk.output('flow').connectTo(sink.input('flow'));
pipeline.init(imgsrc, grey, pyr, harris, kpsrc, clipper, buf, bufpyr, lk, mixer, sink);
// Main loop
let detect = false, clear = false;
(function() {
const canvas = createCanvas(media.width, media.height, video.title);
let keypoints = [], frameReady = false;
async function update()
{
// find new keypoints
harris.capacity = 0;
if(detect) {
if(keypoints.length < 400)
harris.capacity = 2048;
detect = false;
}
// handle new points added by the user
if(userPoints.length > 0) {
keypoints.push(...userPoints);
userPoints.length = 0;
}
// clear all keypoints
if(clear) {
keypoints.length = userPoints.length = 0;
clear = false;
}
// update parameters
kpsrc.keypoints = keypoints;
lk.windowSize = Speedy.Size(Number(windowSize.value), Number(windowSize.value));
lk.levels = Number(levels.value);
lk.discardThreshold = Number(discardThreshold.value);
lk.numberOfIterations = Number(numberOfIterations.value);
lk.epsilon = Number(epsilon.value);
clipper.size = 200;
// run the pipeline
const result = await pipeline.run();
keypoints = result.keypoints;
// repeat
frameReady = true;
setTimeout(update, 1000 / 60);
}
update();
function render()
{
if(frameReady) {
draw(media, canvas);
renderFlowVectors(canvas, keypoints, 3, '#f22');
renderFeatures(canvas, keypoints, 1, '#f22');
}
frameReady = false;
requestAnimationFrame(render);
}
render();
setInterval(() => renderStatus(keypoints), 200);
})();
// play/pause
const playButton = document.getElementById('play');
playButton.onclick = () => video.paused ? video.play() : video.pause();
// video speed
const speedSlider = document.getElementById('speed-slider');
speedSlider.oninput = () => video.playbackRate = speedSlider.value;
// detect features
const detectButton = document.getElementById('detect');
detectButton.onclick = () => detect = true;
// clear features
const clearButton = document.getElementById('clear');
clearButton.onclick = () => clear = true;
// restart the video and clear the features
video.onended = () => {
clear = true;
video.currentTime = 0.2;
video.play();
};
}
function createCanvas(width, height, title)
{
const canvas = document.getElementById('canvas-demo') || document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.title = title;
if(!document.body.contains(canvas))
document.body.appendChild(canvas);
canvas.addEventListener('mousedown', ev => {
const position = cursorPosition(canvas, ev);
userPoints.push({ position });
});
return canvas;
}
function renderFeatures(canvas, features, size = 2, color = 'yellow')
{
const context = canvas.getContext('2d');
context.beginPath();
for(let feature of features) {
let radius = size * feature.scale;
// draw scaled circle
context.moveTo(feature.x + radius, feature.y);
context.arc(feature.x, feature.y, radius, 0, Math.PI * 2.0);
// draw rotation line
const sin = Math.sin(feature.rotation);
const cos = Math.cos(feature.rotation);
context.moveTo(feature.x, feature.y);
context.lineTo(feature.x + radius * cos, feature.y + radius * sin);
}
context.strokeStyle = color;
context.lineWidth = 2;
context.stroke();
}
function renderFlowVectors(canvas, features, length = 1, color = 'red')
{
const context = canvas.getContext('2d');
context.beginPath();
for(let i = 0; i < features.length; i++) {
const feature = features[i];
const flow = feature.flow;
// draw flow vector
context.moveTo(feature.x - flow.x * length, feature.y - flow.y * length);
context.lineTo(feature.x, feature.y);
}
context.strokeStyle = color;
context.lineWidth = 2;
context.stroke();
}
function renderStatus(features)
{
const status = document.getElementById('status');
status.innerText = `FPS: ${Speedy.fps} | Keypoints: ${features.length}`;
}
function draw(media, canvas, x = 0, y = 0, width = media.width, height = media.height)
{
const ctx = canvas.getContext('2d');
ctx.drawImage(media.source, x, y, width, height);
}
function cursorPosition(canvas, event)
{
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
return { x, y };
}
function reset()
{
const options = document.querySelectorAll('select option');
for(const option of options)
option.selected = option.defaultSelected;
const slider = document.getElementById('speed-slider');
slider.value = slider.defaultValue;
slider.dispatchEvent(new Event('input'));
}
</script>
<mark>Powered by <a href="https://github.com/alemart/speedy-vision">speedy-vision.js</a></mark>
</body>
</html>