0
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のGPT-4Vで画像説明すーる(Python)

Last updated at Posted at 2023-12-06

はじめに

がちもとさんアドベントカレンダー6日目の記事です。
今日は、GPT-4Vを用いて画像を説明するプログラム作りました。

開発環境

  • Windows 11 PC
  • Python 3.11

画像URLから画像説明

導入

1.ライブラリのインストール
pip install openai

2.APIキーを発行
https://platform.openai.com/api-keys

3.プログラムを作成

gpt4v.py
from openai import OpenAI
client = OpenAI(api_key="<INSERT-YOUR-API-KEY>")

response = client.chat.completions.create(
  model="gpt-4-vision-preview",
  messages=[
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "何が映っていますか?"}, # "What’s in this image?"
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
          },
        },
      ],
    }
  ],
  max_tokens=300,
)

print(response.choices[0].message.content)
コード解説

1.OpenAIのAPIキーを使用して、OpenAIのサーバーと通信するためのクライアントを作成します。
2.client.chat.completions.createメソッドを使用して、リクエストを送信します。このリクエストには以下の情報が含まれています:

  • model:GPT-4 Visionモデルを指定します。
  • messages:ユーザーからのメッセージと画像の情報を含むリストです。ユーザーが「何が映っていますか?」と尋ねており、画像のURLも提供されています。
  • max_tokens:応答の最大トークン数を設定します。

3.リクエストを送信し、APIからの応答を受け取ります。

4.最後に、APIからの応答から最初の選択肢のメッセージのコンテンツを表示します。

実行結果

何が映っていますか?

画像 説明
image.png この写真には、緑豊かな草地の中を通る木製の遊歩道が映っています。写真の背景に は青い空と白い雲が広がり、自然の美しさと静けさが感じられます。木製の道は一点 透視図法によって視点が遠くに向かって狭くなっており、遠景に向かう視線を導いて います。遊歩道の両側には野草や低木が生い茂り、手つかずの自然環境を思わせるシ ーンです。

画像ファイルから画像説明

導入

gpt4v.py
import base64
import requests

# OpenAI API Key
api_key = "<INSERT-YOUR-API-KEY>"

# Function to encode the image
def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

# Path to your image
image_path = "Gfp-wisconsin-madison-the-nature-boardwalk.jpg"

# Getting the base64 string
base64_image = encode_image(image_path)

headers = {
  "Content-Type": "application/json",
  "Authorization": f"Bearer {api_key}"
}

payload = {
  "model": "gpt-4-vision-preview",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "何が映っていますか?" # "What’s in this image?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": f"data:image/jpeg;base64,{base64_image}"
          }
        }
      ]
    }
  ],
  "max_tokens": 300
}

response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)

print(response.json())

実行結果

{
  "id": "chatcmpl-8SmT62dsyE0KSu8D1HucgXWPi3zhR",
  "object": "chat.completion",
  "created": 1701870188,
  "model": "gpt-4-1106-vision-preview",
  "usage": {
    "prompt_tokens": 1120,
    "completion_tokens": 135,
    "total_tokens": 1255
  },
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "この写真は、草原や湿地を通る 木製の遊歩道が映っています。周囲には緑豊かな草が密生しており、背景には数本の 木や遠くに小さい木々の茂ったエリアが見えます。空は晴れており、青空にはいくつ かの雲が浮かんでいます。自然の美しさと穏やかさを感じさせる風景です。"
      },
      "finish_details": {
        "type": "stop",
        "stop": "<|fim_suffix|>"
      },
      "index": 0
    }
  ]
}

複数画像から画像説明

導入

gpt4v.py
from openai import OpenAI

client = OpenAI(api_key="<INSERT-YOUR-API-KEY>")
response = client.chat.completions.create(
  model="gpt-4-vision-preview",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "何が映っていますか?違いはありますか?", # What are in these images? Is there any difference between them?
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/a/af/Golden_retriever_eating_pigs_foot.jpg",
          },
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/0/08/Cat_Eating_Catgrass.jpg",
          },
        },
      ],
    }
  ],
  max_tokens=300,
)
print(response.choices[0].message.content)

実行結果

何が映っていますか?違いはありますか?

画像1 画像2 画像説明
image.png image.png 最初の画像には、草の上に横たわっているゴールデンレトリバー犬が映っています。 犬は口を開けており、舌が見えます。とても穏やかでリラックスした様子が伝わって きます。二番目の画像には、植物を咥えている白茶トラ猫が映っています。猫はカメラに顔を 向けており、目が大きく開いていて、何かに興味を持っているようです。これら2枚の画像に映っている主な違いは、一枚目が犬を、二枚目が猫を撮影しているという点です。犬と猫は異なる種であり、それぞれ独特の行動や特性を持っています 。犬は一般的に人間との強い絆を持ちやすく、訓練を受けやすい傾向があります。一 方、

お疲れさまでした。

参考文献

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