Skip to content

Instantly share code, notes, and snippets.

@tado
Last active April 20, 2024 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tado/3e41adcb5115253e6ff462faf37b636d to your computer and use it in GitHub Desktop.
Save tado/3e41adcb5115253e6ff462faf37b636d to your computer and use it in GitHub Desktop.
Teachable Machine + p5.js + ml5 テンプレート
<html>
<head>
<meta charset="UTF-8">
<title>Webcam Image Classification using a pre-trained customized model and p5.js</title>
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Teachable Machine実行のためいろいろなJSライブラリーを読み込み -->
<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@latest/dist/ml5.min.js" type="text/javascript"></script>
</head>
<body>
<!-- プログラム本体 -->
<script src="sketch.js"></script>
</body>
</html>
/* ===
Teachable Machine + p5.js + ml5 サンプルコード
事前にTeachable Machineで訓練されたカスタマイズモデルと
p5.js + ml5.jsを使ったウェブカメラ画像の分類。
グー、チョキ、パーの画像を学習
=== */
// 学習してアップロードしたモデルのURL
// !!ここに自分のモデルのURLを入力!!
let imageModelURL = 'https://teachablemachine.withgoogle.com/models/8dyZwOgL4/';
// Classifier変数
let classifier;
// ビデオ
let video;
let flippedVideo;
// 分類結果のラベルを格納
let label = "";
// モデルをプリロード
function preload() {
classifier = ml5.imageClassifier(imageModelURL + 'model.json');
}
function setup() {
createCanvas(640, 500);
// ビデオを設定
video = createCapture(VIDEO);
video.size(640, 480);
video.hide();
flippedVideo = ml5.flipImage(video)
classifyVideo();
}
function draw() {
background(0);
// ビデオを描画
image(flippedVideo, 0, 0);
// 分類結果のラベルを描画
fill(255);
textSize(16);
textAlign(CENTER);
text(label, width / 2, height - 4);
}
// 現在のビデオ画像からラベルを予測
function classifyVideo() {
flippedVideo = ml5.flipImage(video)
classifier.classify(flippedVideo, gotResult);
}
// 分類結果を取得
function gotResult(error, results) {
// エラー処理
if (error) {
console.error(error);
return;
}
// 結果をコンソールに表示
// console.log(results[0]);
// 分類結果のラベルを取得
label = results[0].label;
// 再度分類処理を行う
classifyVideo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment