Created
June 17, 2024 15:11
-
-
Save grapeot/8f1f1a248e04a49da1d9afd4253f3cfd to your computer and use it in GitHub Desktop.
使用GPT-4o识别云量
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import base64 | |
import requests | |
import json | |
def get_cloudiness(image_path): | |
# 读取OpenAI API Key | |
api_key = os.getenv('OPENAI_API_KEY') | |
if not api_key: | |
raise ValueError("API key not found. Please set the 'OPENAI_API_KEY' environment variable.") | |
# 编码图像为base64 | |
def encode_image(image_path): | |
with open(image_path, "rb") as image_file: | |
return base64.b64encode(image_file.read()).decode('utf-8') | |
base64_image = encode_image(image_path) | |
headers = { | |
"Content-Type": "application/json", | |
"Authorization": f"Bearer {api_key}" | |
} | |
payload = { | |
"model": "gpt-4o", | |
"messages": [ | |
{ | |
"role": "user", | |
"content": [ | |
{ | |
"type": "text", | |
"text": "图中云量是多少?输出成JSON,在cloud域内输出0-100的整数. 0是晴天,100是阴天。", | |
}, | |
{ | |
"type": "image_url", | |
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"} | |
} | |
] | |
} | |
], | |
"max_tokens": 50, | |
"response_format": {"type": "json_object"} | |
} | |
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload) | |
response_data = response.json() | |
# 检查响应中是否有云量信息 | |
if 'choices' in response_data and len(response_data['choices']) > 0: | |
content = response_data['choices'][0]['message']['content'] | |
content = json.loads(content) | |
cloudiness = content.get("cloud", None) | |
if cloudiness is not None: | |
return cloudiness | |
else: | |
print(content) | |
raise ValueError("Cloudiness value not found in the response.") | |
else: | |
print(response_data) | |
raise ValueError("Invalid response from the API.") | |
# 示例代码 | |
if __name__ == "__main__": | |
image_paths = ['Cloudy.jpg', 'Moon.jpg', 'Clear.jpg'] | |
try: | |
for image_path in image_paths: | |
cloudiness = get_cloudiness(image_path) | |
print(f"{image_path}, Cloudiness: {cloudiness}") | |
except Exception as e: | |
print(f"Error: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment