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)

输出结果:

相关推荐
土了个豆子的21 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
qq_1728055921 小时前
Go 自建库的使用教程与测试
开发语言·后端·golang
久绊A21 小时前
Hydra-SSH 破解安全防范
开发语言·php
ZZHow102421 小时前
02OpenCV基本操作
python·opencv·计算机视觉
阿昭L21 小时前
c++中获取随机数
开发语言·c++
计算机学长felix1 天前
基于Django的“酒店推荐系统”设计与开发(源码+数据库+文档+PPT)
数据库·python·mysql·django·vue
3壹1 天前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
站大爷IP1 天前
Python随机数函数全解析:5个核心工具的实战指南
python
悟乙己1 天前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
max5006001 天前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频