
TypeScript + webpack + TensorFlow.js を使って画像分類
TypeScript + webpack + TensorFlow.js を使って、ブラウザで画像分類を行う方法をまとめました。
1. 開発環境の準備
開発環境の準備手順は、次のとおり。
(1) Node.js と live-server のインストール。
「Node.js の使い方」参照。
(2) プロジェクトの作成。
$ mkdir classifier
$ cd classifier
$ npm init -y
(3) モジュールのインストール。
$ npm i -D webpack webpack-cli typescript ts-loader
$ npm i -S @tensorflow/tfjs @tensorflow-models/mobilenet
(4) プロジェクトの設定ファイル「package.json」の「scripts」を以下のように変更。
・package.json
"scripts": {
"start": "live-server dist",
"build": "webpack",
"watch": "webpack -w"
},
(5) TypeScriptの設定ファイル「tsconfig.json」をプロジェクトフォルダ直下に作成し、以下のように編集。
・tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"target": "es5",
"module": "es2015"
}
}
2. 画像分類
TensorFlow.jsでの画像分類の手順は次のとおり。
(1) プロジェクトフォルダ直下に src フォルダを生成し、srcフォルダ直下に index.ts を作成し、以下のように編集。
・index.ts
const tf=require('@tensorflow/tfjs')
const mobilenet=require('@tensorflow-models/mobilenet')
// 画像の取得
const img = document.getElementById('img')
// モデルの読み込み
mobilenet.load().then(model => {
// 画像分類
model.classify(img).then(predictions => {
console.log('Predictions: ', predictions)
})
})
(2) プロジェクトフォルダ直下に dist フォルダを生成し、distフォルダ直下に index.html と 画像ファイル cat.jpg を配置。
・index.html
<html>
<head>
<img id="img" src="cat.jpg"></img>
<script type="text/javascript" src="main.js"></script>
</head>
</html>
・cat.jpg
(3) ビルドと実行。
$ npm run build
$ npm run start