Search code examples
javascriptp5.jsml5.js

Drawing images (in p5.js) based on PoseNet


I am using ml5's poseNet in the p5.js web editor to place a funky head image on the face of a user using the webcam. I would like the sketch to draw a warning sign (the image 'warning1.png' in the sketch files) when there is no one in the frame. The sketch can already log 'no one in the frame' when it detects 0 poses, but how can I draw the image warning1.png over the canvas when it's not written in the draw function but in the setup function?

if (poses.length == 0) {
    console.log('no one in the frame')
  }

Same story goes for when there is more than one person in the frame (I am using poseNet's multiPose). The sketch detects +1 person in the frame (and the console logs 'too many people in the frame')...

if (poses.length > 1) {
      console.log('too many people in the frame')
  }

... but how do I draw the image 'warning2.png' over the canvas.

Also, I would like the funkyhead.png image to disappear when one of the above situations occur — now the image is always drawn. Here's my sketch in the p5.js web editor: https://editor.p5js.org/saskiasmith/sketches/_5O_aAzE_

Many thanks!!


Solution

  • You could just create another global variable to keep track of whether the error is currently occuring or not. In gotPoses you can add an else statement to your if statement. And then you set your global variable true or false. In draw you use that same global variable to determine whether to show the image or not.

    So: let noPoseDetected = false;

    in getPoses:

    if (poses.length == 0) {
        console.log('no one in the frame');
        noPoseDetected = true;
      } else {
        noPoseDetected = false;
      }
    

    And then in draw:

    if (noPoseDetected) {
        image(warning1, 0, 0, 50,50);
    }
    

    That shoud work for all your use cases.