gpt-4o看图说话-根据图片回答问题

问题:中国的人口老龄化究竟有多严重?

代码下实现如下:(直接调用openai的chat接口)

import os

import base64

import requests

def encode_image(image_path):

"""

对图片文件进行 Base64 编码

输入:

  • image_path:图片的文件路径

输出:

  • 编码后的 Base64 字符串

"""

二进制读取模式打开图片文件,

with open(image_path, "rb") as image_file:

将编码后的字节串解码为 UTF-8 字符串,以便于在文本环境中使用。

return base64.b64encode(image_file.read()).decode("utf-8")

中文 Prompt 指令

question = "中国的人口老龄化究竟有多严重?"

prompt = (

f"你的任务是根据图片回答问题,{question}详细回答。"

)

对本地多张图片进行 Base64 编码

images = os.listdir("./images")

images.sort()

images.remove('.ipynb_checkpoints')

print(images)

base64_images = [encode_image("./images/" + image) for image in images]

组织用户消息

user_content = [{"type": "text", "text": prompt}]

base64_images = [

{

"type": "image_url",

"image_url": {

"url": f"data:image/jpeg;base64,{base64_image}",

"detail": "high",

},

}

for base64_image in base64_images

]

user_content.extend(base64_images)

messages_template = [{"role": "user", "content": user_content}]

构造请求参数

payload = {

"model": "gpt-4o",

"messages": messages_template,

"max_tokens": 1600,

"temperature": 0,

"seed": 2024,

}

OpenAI API Key

api_key = "sk-xxx"

请求头

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

发送 POST 请求

response = requests.post(

"https://api.openai.com/v1/chat/completions",

headers=headers, json=payload

)

打印生成结果

print(response.json())

result = response.json()["choices"][0]["message"]["content"]

print(result)

输出结果:

相关推荐
u010914760几秒前
C#怎么使用TopLevel顶级语句 C#顶级语句怎么写如何省略Main方法简化控制台程序【语法】
jvm·数据库·python
独隅2 分钟前
PyTorch转TFLite动态形状处理技巧
人工智能·pytorch·python
Shorasul10 分钟前
Go语言goroutine调度原理_Go语言GMP调度模型教程【高效】
jvm·数据库·python
咸鱼翻身小阿橙11 分钟前
QT-P3
开发语言·qt·计算机视觉
Absurd58712 分钟前
Navicat导出JSON数据为空如何解决_过滤条件与权限排查
jvm·数据库·python
m0_7164300714 分钟前
SQL如何高效统计分类下的多项指标_善用CASE WHEN与SUM聚合
jvm·数据库·python
m0_5887584815 分钟前
PHP源码运行受主板供电影响吗_供电相数重要性说明【技巧】
jvm·数据库·python
qq_4138474017 分钟前
如何处理MongoDB跨分片事务报错_4.2+分布式事务的限制与两阶段提交延迟
jvm·数据库·python
InfinteJustice18 分钟前
HTML函数在超频CPU上更流畅吗_超频对HTML函数影响【技巧】
jvm·数据库·python
心易行者19 分钟前
代码写好了,然后呢?——手把手教你把Python脚本变成能赚钱的Web应用
开发语言·前端·python