| """ | |
| 2025 実装 — HuggingFace Transformers を使った画像分類 | |
| 実質 5 行で前処理・推論・後処理がすべて完結する。 | |
| """ | |
| from transformers import pipeline | |
| # モデルのロード(初回のみダウンロード) | |
| classifier = pipeline( | |
| "image-classification", | |
| model="google/vit-base-patch16-224", | |
| ) | |
| def classify(image) -> list[dict]: | |
| """ | |
| Parameters | |
| ---------- | |
| image : PIL.Image | str | |
| PIL 画像オブジェクト、またはファイルパス文字列 | |
| Returns | |
| ------- | |
| list[dict] | |
| [{"label": str, "score": float}, ...] 上位 5 件 | |
| """ | |
| return classifier(image, top_k=5) | |