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)

输出结果:

相关推荐
看到我,请让我去学习6 分钟前
C语言基础(day0424)
c语言·开发语言·数据结构
studyer_domi9 分钟前
Matlab 复合模糊PID
开发语言·matlab
用户8671324957412 分钟前
97% 的 Python 项目可以使用 partial() 更简洁
python
猫猫头有亿点炸27 分钟前
C语言斐波拉契数列2.0
c语言·开发语言·算法
刚入坑的新人编程35 分钟前
C++多态
开发语言·c++
灏瀚星空1 小时前
从单机工具到协同平台:开源交互式模拟环境的技术演进之路
经验分享·笔记·python·开源·oneapi
西柚小萌新1 小时前
【Python爬虫实战篇】--Selenium爬取Mysteel数据
开发语言·爬虫·python
努力写代码的熊大1 小时前
c语言中文件操作详解
c语言·开发语言
QUST-Learn3D1 小时前
高精度并行2D圆弧拟合(C++)
开发语言·c++
天才测试猿1 小时前
软件测试之功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例