Code viewer for World: ML5 image recognition

// ML5 image recognition
// based roughly on this World in the ML5 docs:
// https://learn.ml5js.org/#/reference/image-classifier
// https://github.com/ml5js/ml5-library/tree/main/examples/p5js/ImageClassification/ImageClassification

// Uses neural network 
// ml5.imageClassifier() classifies an image using a pre-trained model.
// The pre-trained model [MobileNet] was trained on a sample of a database of approximately 15 million images.   
// The ml5 library accesses this model from the cloud (from the NPM database).  


 

let classifier;
let img;

const theimage = "/uploads/starter/1623351872.png";   
 // hedgehog
 // https://commons.wikimedia.org/wiki/Category:Erinaceinae
 // https://commons.wikimedia.org/wiki/File:Igel.JPG
 

function preload()
{
    classifier = ml5.imageClassifier('MobileNet');
    img = loadImage(theimage);
}


function setup() 
{
    createCanvas ( img.width, img.height );
    image (img, 0, 0);
 //   AB.msg ( "Running image recognition ... <br> ", 1 );
    
    
    classifier.classify ( img, 5,  function ( error, results )          // classify, with callback function 
    {
        if (error) 
        {
            AB.msg ( "<font color=red> <B> Error recognising image. See console for details. </b></font> <br> ", 2 );
            console.log (error);
        }
        
        // results = an array ordered by confidence
        var r = "<hr> <h3> Rank Confidence Identification </h3> ";
        
        for ( var i = 0; i < results.length; i++ )
        {
            r = r + (i+1) + ". " + nf(results[i].confidence, 0, 2) + " " + results[i].label + " <br> ";
            // https://p5js.org/reference/#/p5/nf
        }
        
        AB.msg ( r, 3 );
    });
}


// no draw() function