Created
July 29, 2019 04:30
-
-
Save iddar/dd94762300f58cef7d0534db920c487a to your computer and use it in GitHub Desktop.
Ball tracking example with Node JS and OpenCV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ball tracking example with Node JS and OpenCV | |
// Before running this script please check de opencv4nodejs installation steps | |
// Dependencies: https://www.npmjs.com/package/opencv4nodejs | |
// Inspired by: https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/ | |
// Author Iddar Olivares <https://github.com/iddar> July 2019 | |
const cv = require('opencv4nodejs'); | |
const delay = 1 | |
const devicePort = 0; | |
const vCap = new cv.VideoCapture(devicePort); | |
// important values | |
const method = cv.HOUGH_GRADIENT; | |
const dp = 2; | |
const minDist = 50; | |
const resolution = 280 | |
function onFrame(frame) { | |
const bw = frame.cvtColor(cv.COLOR_BGR2GRAY) | |
const circles = bw.houghCircles(method, dp, minDist) | |
drawBall(bw, circles) | |
cv.imshow('frame', bw); | |
} | |
function drawBall (dstImg, circles) { | |
circles.forEach(({x, y, z}) => { | |
const blue = new cv.Vec(255, 0, 0); | |
const orange = new cv.Vec(0, 128, 255); | |
dstImg.drawCircle(new cv.Point2(x, y), z, { color: blue, thickness: 2 }) | |
dstImg.drawRectangle( | |
new cv.Point(x - 5, y - 5), | |
new cv.Point(x + 5, y + 5), | |
{ color: orange, thickness: 1 } | |
); | |
}) | |
} | |
/** | |
* runner | |
* Call onFrame every frame | |
*/ | |
const runner = setInterval(() => { | |
let frame = vCap.read(); | |
// loop back to start on end of stream reached | |
if (frame.empty) { | |
vCap.reset(); | |
frame = vCap.read(); | |
} | |
let resized = frame.resizeToMax(resolution) | |
// let ratio = frame.sizes[0] / parseFloat(resized.sizes[0]) | |
onFrame(resized); | |
const key = cv.waitKey(delay); | |
done = key !== -1 && key !== 255; | |
if (done) { | |
clearInterval(runner); | |
console.log('Key pressed, exiting.'); | |
} | |
}, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment