Skip to content

Instantly share code, notes, and snippets.

@MForMarlon
Created January 12, 2019 00:16
Show Gist options
  • Save MForMarlon/90737048873655c9cedcbb0455cd6510 to your computer and use it in GitHub Desktop.
Save MForMarlon/90737048873655c9cedcbb0455cd6510 to your computer and use it in GitHub Desktop.
Pedestrian tracker using HOG Descriptor and opencv4nodejs
// based from https://github.com/justadudewhohacks/opencv4nodejs/tree/master/examples/simpleTracking1.js
// This code is meant to be run on a Raspberry Pi 3 with the picamera.
// NOTE: Before running this code, for OpenCV to detect the camera, you need to run sudo modprobe bcm2835-v4l2
// TODO: Write each detected frame to an image file somewhere, with the timestamp in the name
const cv = require('opencv4nodejs');
const delay = 50;
const hog = new cv.HOGDescriptor();
hog.setSVMDetector(cv.HOGDescriptor.getDefaultPeopleDetector());
// first arg = camera source or path to file name
const grabFrames = (videoFile, delay, onFrame) => {
const cap = new cv.VideoCapture(videoFile);
let done = false;
const intvl = setInterval(() => {
// flipcodes: 0 = around x, 1 = around y, -1 = around both
let frame = cap.read().flip(0);
// loop back to start on end of stream reached
if (frame.empty) {
cap.reset();
frame = cap.read();
}
onFrame(frame);
const key = cv.waitKey(delay);
done = key !== -1 && key !== 255;
if (done) {
clearInterval(intvl);
console.log('Key pressed, exiting.');
}
}, 0);
};
// 0 arg streams from the picamera
grabFrames(0, delay, frame => {
// setting the max from 300 to 320 will make this work decently.
// if we make it smaller than 300, the detector won't work.
// if bigger, the performance greatly suffers.
const grayImg = frame.resizeToMax(320).bgrToGray();
const multiScaleResult = hog.detectMultiScale(grayImg);
if (multiScaleResult.foundLocations && multiScaleResult.foundLocations.length) {
multiScaleResult.foundLocations.forEach(location => {
grayImg.drawRectangle(new cv.Point(location.x, location.y),
new cv.Point(location.x + location.width, location.y + location.height),
new cv.Vec(0, 255, 0), 2); // bgr vector for color, thickness
});
console.log(multiScaleResult.foundLocations, multiScaleResult.foundWeights, new Date());
}
cv.imshow('hog', grayImg);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment