2
3

TensorFlow.js  ブラウザで画像ファイルからのオブジェクト検出するゲーム。

Last updated at Posted at 2024-09-05

スクリーンショット 2024-09-06 045642.png

image.png

画像ファイルをローカルPCから選択してオブジェクト検出を行うコードです。TensorFlow.jsのCOCO-SSDモデルを使用して、ファイル選択後に画像内のオブジェクトを検出します。

ブラウザページ再読み込みで別画像でオブジェクト検出できます。
(ページ下部にボタンあります。)

image.png

image.png

image.png

image.png

image.png

image.png

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Object Detection with TensorFlow.js (Image File)</title>
  <style>
    canvas {
      border: 1px solid black;
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <h1>Object Detection with TensorFlow.js</h1>
  <input type="file" id="imageUpload" accept="image/*" />
  <canvas id="canvas"></canvas>

  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
  <script>
    const imageUpload = document.getElementById('imageUpload');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 画像が選択されたときの処理
    imageUpload.addEventListener('change', async (event) => {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;
          img.onload = async () => {
            // キャンバスに画像を描画
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);

            // COCO-SSDモデルのロード
            const model = await cocoSsd.load();
            
            // 物体検出
            const predictions = await model.detect(img);

            // 検出結果を描画
            predictions.forEach(prediction => {
              const [x, y, width, height] = prediction.bbox;
              ctx.strokeStyle = '#00FF00';
              ctx.lineWidth = 2;
              ctx.strokeRect(x, y, width, height);
              ctx.font = '18px Arial';
              ctx.fillStyle = '#00FF00';
              ctx.fillText(
                `${prediction.class} (${Math.round(prediction.score * 100)}%)`,
                x, y > 10 ? y - 5 : 10
              );
            });
          };
        };
        reader.readAsDataURL(file);
      }
    });
  </script>
</body>
</html>

説明
ファイル選択: を使用して、ユーザーがローカルPCから画像ファイルを選択できるようにしています。
画像表示: JavaScriptのFileReaderを使用して、選択された画像ファイルを読み込み、キャンバスに描画します。
COCO-SSDモデルの使用: TensorFlow.jsのcoco-ssdモデルを使用して、画像内のオブジェクト検出を行います。
結果描画: 検出されたオブジェクトのバウンディングボックスとクラス名をキャンバス上に描画します。
これにより、ローカルPCから画像を選択して、物体検出をブラウザ上で実行できるようになります。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3