1. 引言
在本部分,我们详细介绍如何在代码中导入图片,并让 ChatGPT 进行评价。重点包括如何遍历文件夹中的图片、如何对图片进行处理(转换为 Base64 编码)、如何构造 API 请求、如何解析 ChatGPT 的返回结果并保存。
2. 代码修改
在原有调用 ChatGPT 进行文本交互的代码基础上,我们增加了以下改动,使其可以读取本地图片并发送至 ChatGPT 进行评价。
2.1 遍历文件夹中的所有图片
首先,我们需要遍历指定的文件夹,提取所有图片的文件路径。
import os
def get_image_files(folder_path, extensions=(".jpg", ".png", ".jpeg")):
""" 获取文件夹内所有符合格式的图片文件 """
image_files = []
for root, _, files in os.walk(folder_path): # 遍历文件夹
for file in files:
if file.lower().endswith(extensions): # 筛选符合格式的图片
image_files.append(os.path.join(root, file))
return image_files
# 示例用法
image_folder = "./images"
image_files = get_image_files(image_folder)
print(f"找到 {len(image_files)} 张图片")
作用:
os.walk()
遍历文件夹及其所有子目录。过滤掉非图片文件,仅获取
.jpg
、.png
、.jpeg
文件。返回所有符合条件的图片路径。
这样,无论你的图片存放在什么层级的文件夹中,该方法都可以正确找到并返回所有图片。
2.2 读取图片并转换为 Base64 编码
ChatGPT 需要通过 Base64
格式读取图片,因此我们需要实现一个编码函数。
import base64
def encode_image(image_path):
""" 读取图片并转换为 Base64 编码 """
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
作用:
以二进制格式读取图片。
使用
base64.b64encode()
进行编码。转换为字符串格式,便于 API 传输。
2.3 构造 ChatGPT API 请求
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def generate_payload(image_base64):
""" 构造 API 请求 """
return {
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "请评价这张图片。"},
{"role": "user", "content": [
{"type": "text", "text": "请评价这张图片。"},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}}
]}
],
"max_tokens": 500
}
作用:
messages
结构包含文本和图片。image_url
以Base64
形式传递图片数据,确保 API 能正确解析。
2.4 发送请求并处理 API 响应
import requests
import time
def send_request(payload):
""" 发送 API 请求并处理返回数据 """
for attempt in range(5): # 增加重试机制
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
json=payload,
headers=headers,
timeout=60
)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
elif response.status_code == 429:
print(f"请求速率受限,等待 {2 ** attempt} 秒后重试...")
time.sleep(2 ** attempt)
else:
print(f"请求失败: {response.status_code}, {response.text}")
break
except requests.exceptions.RequestException as e:
print(f"❌ 请求失败: {e}")
break
return None
作用:
requests.post()
发送 API 请求。如果 API 速率受限(429 错误),指数级回退重试。
解析 API 返回的 JSON 数据,提取评价文本。
2.5 批量处理图片并保存评价结果
all_evaluations = []
for image_path in image_files:
image_base64 = encode_image(image_path)
payload = generate_payload(image_base64)
evaluation = send_request(payload)
if evaluation:
all_evaluations.append(f"图片: {image_path}\n评价: {evaluation}\n\n")
# 保存评价结果
with open("evaluation_results.txt", "w", encoding="utf-8") as file:
file.writelines(all_evaluations)
print("✅ 所有图片的评价已保存!")
作用:
遍历所有图片,对每张图片进行编码、发送请求,并获取 ChatGPT 的评价。
将所有评价存入
evaluation_results.txt
文件,方便后续查看。
3. 结论
通过修改,我们成功让 ChatGPT 处理图片并提供评价。具体步骤包括:
遍历文件夹,找到所有图片文件。
读取图片并转换为 Base64 编码,符合 API 规范。
构造 API 请求,将文本和图片数据传输至 ChatGPT。
发送请求并处理 API 响应,包括重试机制。
存储评价结果,保存到本地文件。
通过这种方法,我们可以高效地批量评估多张图片,并获取详细的评价结果。