iT邦幫忙

3

拿 ml5 來練習 Markdown 語法 (一)

介紹

首先介紹什麼是 ml5,
ml5 是基於 TensorFlow.js 在瀏覽器中提供友善的機械學習使用介面。(https://github.com/ml5js/ml5-library)

備料

接著備料,

  1. 新增一資料夾,名稱 hello-ml5
  2. 使用 VS Code 打開此資料夾,在 hello-ml5 裡新增一檔案,檔名 index.html
  3. 確認 VS Code 有安裝 Live Server 擴充。https://ithelp.ithome.com.tw/upload/images/20201027/201321566BhHGDdu8Z.png
  4. index.html 輸入以下程式碼。
<html>

<head>
    <meta charset="UTF-8">
    <title>Image classification using MobileNet and p5.js</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
    <script src="https://unpkg.com/ml5@0.4.3/dist/ml5.min.js"></script>
</head>

<body>
    <h1>Image classification using MobileNet and p5.js</h1>
    <script src="sketch.js"></script>
</body>

</html>
  1. hello-ml5 裡新增一檔案,檔名 sketch.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/dog.jpg');
}

function setup() {
  createCanvas(400, 400);
  classifier.classify(img, gotResult);
  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);
  } else {
    // 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)}`);
  }
}
  1. hello-ml5 裡新增一資料夾,名稱 images,並在此資料夾放入一張如下的圖片,名為 dog.jpg
    https://ithelp.ithome.com.tw/upload/images/20201027/20132156BTOt25dSoR.jpg

執行

備料完成後,就可啟動 Live Server,
啟動方式可參照 (https://mnya.tw/cc/word/1430.html)。

啟動後,會出現預設的瀏覽器視窗,
視窗內容應如下。
https://ithelp.ithome.com.tw/upload/images/20201027/201321563BKcEk9uXK.png

假設預設瀏覽器是 Chrome,按下 F12 鍵,在開發人員工具中,選擇 Console 標籤,
展開內容,應出現如下訊息。
https://ithelp.ithome.com.tw/upload/images/20201027/20132156omghHyjYoA.png

ml5 所提供的機械學習介面告知我, dog.jpg 的圖片內容最有可能為拉布拉多犬 (Labrador retriever),
我認為也是如此。

測試

images 資料夾裡放入一張 cat.jpg 的圖片,並將 sketch.js 檔案裡的程式碼,

img = loadImage('./images/dog.jpg');

改成

img = loadImage('./images/cat.jpg');

,結果如下。
https://ithelp.ithome.com.tw/upload/images/20201027/20132156qX3bjFycvC.png
辨識結果為花貓 (tabby, tabby cat),
與我的認知相同。

所以,透過 ml5 所提供的機械學習介面,可完成圖片識別的需求。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言