Skip to content

01图像分类

这个实例实现图片识别功能,可以判断出图片上的物体名称,类似识别植物名称的APP形色。

新建index.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
    <script src="https://unpkg.com/ml5@latest/dist/ml5.min.js" type="text/javascript"></script>
  </head>

  <body>
    <script src="sketch.js"></script>
  </body>
</html>

Tip

需要注意ml5.js要放在p5.js文件的后面,否则会报错。

新建sketch.js文件

// Initialize the Image Classifier method with MobileNet. A callback needs to be passed.
let classifier;

// A variable to hold the image we want to classify
let img;

function preload() {
  classifier = ml5.imageClassifier('MobileNet');
  img = loadImage('images/bee2.jpg');
}

function setup() {
  createCanvas(400, 400);
  classifier.classify(img, gotResult);
  img.resize(width, 0);
  image(img, 0, 0,);
}

// A function to run when we get any errors and the results
function gotResult(error, results) {
  // Display error in the console
  if (error) {
    console.error(error);
  }
  // The results are in an array ordered by confidence.
  console.log(results);
  createDiv('Label: ' + results[0].label);
  createDiv('Confidence: ' + nf(results[0].confidence, 0, 2));
}

深蹲练习APP

https://colab.research.google.com/drive/1OHTsNyr3Ry_bSw8dT9s77BZsXHe7i8HR#scrollTo=uIbljMew7Wje