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

watsonx.ai APIを使った画像認識Webアプリの作り方

Last updated at Posted at 2025-11-04

この記事では、IBM watsonx.aiのAPIを利用して画像認識Webアプリを構築する手順を紹介します。


動作環境

  • Python:3.9以上推奨
  • 必要ライブラリ:
    • ibm-watsonx-ai
    • base64
  • IBM Cloudアカウント(Free Trial可)
  • watsonx.aiのProject ID、URL、API Key、モデルID

事前準備

  1. IBM watsonx.ai で Free Trialアカウントを作成 またはログイン。
  2. ログイン後、Projectを作成し、Developer Accessから以下を取得:
    • Project ID
    • watsonx.ai URL
    • API Key
  3. 画像を処理できるVision系のモデルを選択
    Models – IBM watsonx Developer Hub

watsonx APIの設定

必要なライブラリをインポートし、Credentials、APIClient、ModelInferenceを設定します。

from ibm_watsonx_ai import APIClient, Credentials
from ibm_watsonx_ai.foundation_models import ModelInference
import base64

credentials = Credentials(
    url="Your watsonx.ai URL",
    api_key="Your API Key",
)
client = APIClient(credentials)
model = ModelInference(
    model_id="Your model id",
    api_client=client,
    project_id="Your Project ID"
)

画像とプロンプトを渡す

画像をBase64でエンコードし、プロンプトと一緒にモデルに渡します。

encoded_string = base64.b64encode(uploaded_file.read()).decode('utf-8')
prompt = "Your prompt"

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": prompt},
            {
                "type": "image_url",
                "image_url": {"url": "data:image/jpeg;base64," + encoded_string}
            }
        ]
    }
]

default_text = model.chat(messages=messages)["choices"][0]["message"]["content"] or ""

処理を書く

これでwatsonx APIに画像を渡し、モデルで処理した結果を取得できます。
あとは、目的に合わせてWebアプリを構築してください。

参考文献・参考コード

書籍名:『仕組みからわかる大規模言語モデル 生成AI時代のソフトウェア開発入門』
(奥田 勝己著、翔泳社、2025年)
サンプルコード公開先:https://github.com/katsumiok/llm-book

※本記事で紹介するコードは、上記サンプルコードを直接利用したものではなく、APIの使い方や設計の考え方を参考にして独自に作成したものです。

関連リンク

IBM watsonx Developer Hub
https://www.ibm.com/watsonx/developer/

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