基于OpenAI API接口向GPT4v上传图像进行图像分析

复制代码
import openai
import base64
from openai import OpenAI


client = OpenAI(
    api_key='xxxxxxxxx',  
    base_url='https://api.openai.com/v1'#可根据镜像站修改
)

#图片转base64函数
def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')
 
#输入图片路径
image_path = "xxxxxx"
 
#原图片转base64
base64_image = encode_image(image_path)


#提交信息至GPT4o
response = client.chat.completions.create(
    model="xxx",#选择模型
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content":[
            {
          "type": "text",
          "text": "xxxxxxxxxxxxxxxxxx"
        },
                    {
          "type": "image_url",
          "image_url":{
            "url": f"data:image/jpeg;base64,{base64_image}"
          }
        },
        ]
        }
    ],
    stream=True,
)

reply = ""
for res in response:
    content = res.choices[0].delta.content
    if content:
        reply += content
        print(content)

print('reply:',reply)
复制代码

 

posted @   Victooor_swd  阅读(1980)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示