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)

输出结果:

相关推荐
MediaTea6 分钟前
Python 第三方库:OpenPyXL(Excel 文件读写与操作)
开发语言·python·excel
点云SLAM11 分钟前
C++ 中dynamic_cast使用详解和实战示例
开发语言·c++·类型转换·dynamic_cast·c++多态·c++继承
CodeByV28 分钟前
【C++】C++11:右值引用和移动语义
开发语言·c++
一水鉴天32 分钟前
整体设计 全面梳理复盘 之37 元级自动化引擎三体项目(Designer/Master/Transformer)划分确定 + 自用规划工具(增强版)
开发语言·算法·transformer·公共逻辑
自学互联网1 小时前
python爬虫入门案例day05:Pexels
开发语言·爬虫·python
头发还没掉光光1 小时前
C/C++类型转换
c语言·开发语言·c++
馨谙1 小时前
RHEL 存储堆栈完全解析:从硬件到应用的存储管理指南
服务器·开发语言·php
二川bro1 小时前
第38节:WebGL 2.0与Three.js新特性
开发语言·javascript·webgl
再__努力1点1 小时前
【11】特征检测与匹配:AKAZE特征算法详解与实现
人工智能·python·opencv·算法·计算机视觉·特征提取
麦麦大数据1 小时前
F046 新闻推荐可视化大数据系统vue3+flask+neo4j
python·flask·vue3·知识图谱·neo4j·推荐算法