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)

输出结果:

相关推荐
ac-er88882 分钟前
在Flask中处理后台任务
后端·python·flask
ac-er88888 分钟前
Flask中的钩子函数
后端·python·flask
o独酌o12 分钟前
递归的‘浅’理解
java·开发语言
Book_熬夜!15 分钟前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
我的运维人生24 分钟前
利用Python与Ansible实现高效网络配置管理
网络·python·ansible·运维开发·技术共享
毕设木哥31 分钟前
计算机专业毕业设计推荐-基于python的汽车汽修保养服务平台
大数据·python·计算机·django·汽车·毕业设计·课程设计
m0_6312704042 分钟前
高级c语言(五)
c语言·开发语言
2401_858286111 小时前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
程序猿练习生1 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
2401_858120261 小时前
MATLAB中的无线通信系统部署和优化工具有哪些
开发语言·matlab