2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenAI APIを使用し画像を送信する

Last updated at Posted at 2024-09-12

OpenAI APIを使用して、画像の送信方法を紹介します。

実施環境

環境 バージョン
OS Windows11
Python 3.11.0
OpenAI Python API library 1.43.0

事前準備

APIキーの準備

OpenAIの公式サイトからAPIキーを取得してください。


OpenAI Python API libraryインストール

pip install openai

Web上の画像の送信

Web上にアップロードされている画像の送信方法です。「IMG_URL」に画像のURLを記載してください。また、「YOUR_API_KEY」に事前準備で取得したAPIキーを記載してください。

imgOpenAi.py
from openai import OpenAI

client = OpenAI(
    #事前準備で取得したAPIキー
    api_key = "YOUR_API_KEY",
    base_url = 'https://api.openai.com/v1/chat/completions'
)
res = client.chat.completions.create(
    model = "gpt-4o-mini",
    messages = [
        {
            "role":"user",
            "content":[
                {
                    "type": "text",
                    "text": "画像に書かれている文字は何ですか?書いている文字だけ教えてください"
                },   
                {    
                    "type": "image_url",
                    "image_url":
                    {
                        #画像のURL
                        "url": "IMG_URL"
                    } 
                }
            ]
        }
    ]
)

print(res.choices[0])

ローカル画像の送信

ローカル画像の送信は、画像をBase64形式に変換することで送信できます。

localimgOpenAi.py
import base64
from openai import OpenAI

#画像をBase64形式に変換する関数
def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

#画像をBase64形式に変換
img = encode_image(image_Path)

client = OpenAI(
    #事前準備で取得したAPIキー
    api_key = "YOUR_API_KEY",
    base_url = 'https://api.openai.com/v1/chat/completions'
)
res = client.chat.completions.create(
    model = "gpt-4o-mini",
    messages = [
        {
            "role":"user",
            "content":[
                {
                    "type": "text",
                    "text": "画像に書かれている文字は何ですか?書いている文字だけ教えてください"
                },   
                {    
                    "type": "image_url",
                    "image_url":
                    {
                        #画像のURL
                        "url": f"data:image/png;base64,{img}"
                    } 
                }
            ]
        }
    ]
)

#受信したメッセージを表示
print(res.choices[0])

最後に

OpenAI APIを使用して画像を送信するコードを実装してみました。ローカル環境の画像も送信することができるため、とても便利だと感じました。
アップロードできる画像サイズは20MBまでなので注意してください。

この記事を今後の参考にしていただければ幸いです。ありがとうございました。

参考情報

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?