xxxxxxxxxx
90
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* ===
ml5 Example
PoseNet example using p5.js
=== */
let video;
let poseNet;
let yes = [];
function setup() {
createCanvas(640, 480);
video = createCapture(VIDEO);
video.size(width, height);
// Create a new poseNet method with a single detection
poseNet = ml5.poseNet(video, modelReady);
// This sets up an event that fills the global variable "poses"
// with an array every time new poses are detected
poseNet.on('pose', bodiesTracked);
// Hide the video element, and just show the canvas
video.hide();
}
function modelReady() {
select('#status').html('Model Loaded');
}
function draw() {
// Nothing to see here in this example
}
// A function to draw ellipses over the detected keypoints
function bodiesTracked(bodies) {
image(video, 0, 0, width, height);
//background(0, 5);
// Loop through all the bodies
for (let body of bodies) {
bodyTracked(body.pose);
}
}
function bodyTracked(body) {
// Grab the joints
let joints = body.keypoints;
// Draw all the joints
for (let joint of joints) {
drawJoint(joint);
}
// Pick a joint to track
let joint = body.nose;
// Calculate the distance
let y = joint.y;
yes.push(y);
// Only keep most recent 120 data points
if (yes.length > 60) yes.shift();
// Calculate the average y position
let avgY = 0;
// Add up all the y-values
for (let y of yes) {
avgY += y;
}
// Divide by the number of y-values
avgY /= yes.length;
noStroke();
// Draw y-position of the joint
ellipse(width / 4, y, 50, 50);
// Draw the average y-position of the joint
ellipse(3 * width / 4, avgY, 50, 50);
}
// Draw the joint
function drawJoint(joint) {
// Exit out of function if confidence level is too low
if (joint.score < 0.2) return;
// Get the position of the joint
let pos = joint.position;
stroke('red');
strokeWeight(5);
// Draw the joint at it's x,y position
point(pos.x, pos.y);
}