1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Colab で新規ノートブック作成

コード

#ライブラリをインストール
#!pip install: ColabでPythonパッケージをインストールするコマンドです(!はColabのシェルコマンド)。
#gradio: Webアプリを簡単に作れるライブラリ(画像アップロードUIなど)
#tensorflow: AI・機械学習ライブラリ。画像分類モデル(MobileNetV2)を使うために必要。
#--quiet: インストール時の出力を抑えるオプション。
!pip install gradio tensorflow --quiet

import gradio as gr
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.preprocessing import image
import numpy as np

#ImageNetという大規模データで学習済みの MobileNetV2 モデルを使います。
#自分で学習させる必要はありません(すぐ使えるAI)。
model = MobileNetV2(weights='imagenet')

#ユーザーがアップロードした画像を受け取り、分類する関数です。
def classify_img(img):
#モデルが必要とするサイズ(224x224)にリサイズし、数値配列に変換。
    img = image.img_to_array(img.resize((224, 224)))
#1枚の画像 → バッチ形式(複数枚に見せかける形)に整形。
    img = np.expand_dims(img, axis=0)
#MobileNetV2用にピクセル値を正規化(-1〜1などに調整)。
    img = preprocess_input(img)
#AIモデルに画像を渡して予測(1000カテゴリの確率が返る)。
    preds = model.predict(img)
#数値の結果を人間が理解できる「ラベル」に変換。
    results = decode_predictions(preds, top=3)[0]
#上記を {ラベル: 確率} の辞書形式に変換。
    return {label: float(confidence) for (_, label, confidence) in results}

# グラディオUI
#fn=classify_img: 実行する関数
#inputs=gr.Image(...): 入力は画像(PIL形式)
#outputs="label": 出力は分類ラベル
app = gr.Interface(fn=classify_img, inputs=gr.Image(type="pil"), outputs="label")
#ブラウザにUIを立ち上げて、実際に使えるようにします。
app.launch()

分析画面

ブラウザに画像アップロードUIが出る。画像を入れると → AIが分類してくれる。
スクリーンショット 2025-06-30 6.58.07.png

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?