-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sketch.js
88 lines (78 loc) · 2.62 KB
/
Sketch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* ===
ml5 Example
PoseNet using p5.js
=== */
/* eslint-disable */
// Grab elements, create settings, etc.
var video = document.getElementById("video");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// The detected positions will be inside an array
let poses = [];
// Create a webcam capture
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.srcObject = stream;
video.play();
});
}
// A function to draw the video and poses into the canvas.
// This function is independent of the result of posenet
// This way the video will not seem slow if poseNet
// is not detecting a position
function drawCameraIntoCanvas() {
// Draw the video element into the canvas
ctx.drawImage(video, 0, 0, 640, 480);
// We can call both functions to draw all keypoints and the skeletons
drawKeypoints();
drawSkeleton();
window.requestAnimationFrame(drawCameraIntoCanvas);
}
// Loop over the drawCameraIntoCanvas function
drawCameraIntoCanvas();
// Create a new poseNet method with a single detection
const poseNet = ml5.poseNet(video, modelReady);
poseNet.on("pose", gotPoses);
// A function that gets called every time there's an update from the model
function gotPoses(results) {
poses = results;
}
function modelReady() {
console.log("model ready");
poseNet.multiPose(video);
}
// A function to draw ellipses over the detected keypoints
function drawKeypoints() {
// Loop through all the poses detected
for (let i = 0; i < poses.length; i += 1) {
// For each pose detected, loop through all the keypoints
for (let j = 0; j < poses[i].pose.keypoints.length; j += 1) {
let keypoint = poses[i].pose.keypoints[j];
// Only draw an ellipse is the pose probability is bigger than 0.2
if (keypoint.score > 0.2) {
ctx.beginPath();
ctx.arc(keypoint.position.x, keypoint.position.y, 10, 0, 2 * Math.PI);
ctx.stroke();
}
}
}
}
// A function to draw the skeletons
function drawSkeleton() {
// Loop through all the skeletons detected
for (let i = 0; i < poses.length; i += 1) {
// For every skeleton, loop through all body connections
for (let j = 0; j < poses[i].skeleton.length; j += 1) {
let partA = poses[i].skeleton[j][0];
let partB = poses[i].skeleton[j][1];
ctx.beginPath();
ctx.moveTo(partA.position.x, partA.position.y);
ctx.lineTo(partB.position.x, partB.position.y);
ctx.stroke();
}
}
}