ml5.js
ml5.js 提供了简单的接口来加载和使用机器学习模型,如图像分类、文本生成、姿态估计等,不需要深入理解底层的数学原理或复杂的编程技巧
ml5.js 构建在 TensorFlow.js 之上,提供了一系列预训练模型和简易的 API 接口
图片识别
先进行一个简单的图片识别demo (这里我使用的是汽车图片)
- 首先创建一个index.html
- 引入必要的库
创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.1/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.1/addons/p5.sound.min.js"></script>
<script src="https://unpkg.com/ml5@1/dist/ml5.min.js"></script>
<meta charset="utf-8" />
</head>
<style>
html,
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
</style>
<body>
<main></main>
<script src="sketch.js"></script>
</body>
</html>
创建sketch.js
// 图像分类器
let classifier
// 图像
let img
// 结果
let result
function setup() {
// 创建幕布
createCanvas(400, 400)
// 图像分类器初始化完成后调用classify函数
if (classifier) {
classifier.classify(img, (res, error) => {
if (error) {
console.error(error)
return
}
result = res
console.log(res)
})
} else {
console.error('图像分类器未初始化完成')
}
}
function draw() {
// 绘制背景
background(220)
if (img) {
image(img, 0, 0, width, height)
}
// 绘制结果
if (result) {
fill(255)
stroke(0)
textSize(18)
label = 'Label: ' + result[0].label
confidence = 'Confidence: ' + nf(result[0].confidence, 0, 2)
text(label, 10, 360)
text(confidence, 10, 380)
}
}
function preload() {
// 图像分类器初始化
classifier = ml5.imageClassifier('MobileNet', function () {
console.log('图像分类器初始化完成')
})
img = loadImage('https://picsum.photos/id/133/2742/1828')
}
function gotResult(res, error) {
if (error) {
console.error(error)
return
}
result = res
console.log(results)
}