How to load a local image to gpt4 -vision using API

import os

This code is for v1 of the openai package: openai · PyPI

pip install openai

pip install requests

from openai import OpenAI
import base64
import requests

my_api_key = os.environ[“OPENAI_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 = “.\SourceImages\some_text.jpg”

Getting the base64 string

base64_image = encode_image(image_path)

Loads a local image file and OCRs it.

https://platform.openai.com/docs/guides/vision

headers = {
“Content-Type”: “application/json”,
“Authorization”: f"Bearer {my_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
}

try:

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

except Exception as ex:
print(“Exception:”, ex)

3 Likes