|
| 1 | +/* |
| 2 | + * 👋 Hello! This is an ml5.js example made and shared with ❤️. |
| 3 | + * Learn more about the ml5.js project: https://ml5js.org/ |
| 4 | + * ml5.js license and Code of Conduct: https://github.com/ml5js/ml5-next-gen/blob/main/LICENSE.md |
| 5 | + * |
| 6 | + * This example demonstrates UV mapping with ml5.faceMesh. |
| 7 | + */ |
| 8 | + |
| 9 | +let faceMesh; |
| 10 | +let video; |
| 11 | +let faces = []; |
| 12 | +let options = { maxFaces: 1, refineLandmarks: false, flipped: true }; |
| 13 | + |
| 14 | +let uvMapImage; |
| 15 | + |
| 16 | +let triangulation; |
| 17 | +let uvCoords; |
| 18 | + |
| 19 | +function preload() { |
| 20 | + // Load the faceMesh model |
| 21 | + faceMesh = ml5.faceMesh(options); |
| 22 | + uvMapImage = loadImage("clouds.jpg"); |
| 23 | +} |
| 24 | + |
| 25 | +function setup() { |
| 26 | + createCanvas(640, 480, WEBGL); |
| 27 | + // Create the webcam video and hide it |
| 28 | + video = createCapture(VIDEO); |
| 29 | + video.size(640, 480); |
| 30 | + video.hide(); |
| 31 | + // Start detecting faces from the webcam video |
| 32 | + faceMesh.detectStart(video, gotFaces); |
| 33 | + // Get the Coordinates for the uv mapping |
| 34 | + triangulation = faceMesh.getTriangles(); |
| 35 | + uvCoords = faceMesh.getUVCoords(); |
| 36 | +} |
| 37 | + |
| 38 | +function draw() { |
| 39 | + translate(-width / 2, -height / 2); |
| 40 | + background(51); |
| 41 | + |
| 42 | + for (let i = 0; i < faces.length; i++) { |
| 43 | + let face = faces[i]; |
| 44 | + |
| 45 | + // Draw all the triangles |
| 46 | + noStroke(); |
| 47 | + texture(uvMapImage); |
| 48 | + textureMode(NORMAL); |
| 49 | + beginShape(TRIANGLES); |
| 50 | + for (let i = 0; i < triangulation.length; i++) { |
| 51 | + let indexA = triangulation[i][0]; |
| 52 | + let indexB = triangulation[i][1]; |
| 53 | + let indexC = triangulation[i][2]; |
| 54 | + let a = face.keypoints[indexA]; |
| 55 | + let b = face.keypoints[indexB]; |
| 56 | + let c = face.keypoints[indexC]; |
| 57 | + const uvA = { x: uvCoords[indexA][0], y: uvCoords[indexA][1] }; |
| 58 | + const uvB = { x: uvCoords[indexB][0], y: uvCoords[indexB][1] }; |
| 59 | + const uvC = { x: uvCoords[indexC][0], y: uvCoords[indexC][1] }; |
| 60 | + vertex(a.x, a.y, uvA.x, uvA.y); |
| 61 | + vertex(b.x, b.y, uvB.x, uvB.y); |
| 62 | + vertex(c.x, c.y, uvC.x, uvC.y); |
| 63 | + } |
| 64 | + endShape(); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +// Callback function for when faceMesh outputs data |
| 69 | +function gotFaces(results) { |
| 70 | + // Save the output to the faces variable |
| 71 | + faces = results; |
| 72 | +} |
0 commit comments