参考基于阿里百炼大模型图片理解的代码,设计一个程序能够拍照和上传图片,并理解图片内容,使用Python实现,参考模型如下:#基于阿里百炼大模型的图片理解 import os from openai import OpenAI client = OpenAI( api_key="sk-xxx", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", ) completion = client.chat.completions.create( model="qwen-vl-plus", # 此处以qwen-vl-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models messages=[{"role": "user","content": [ {"type": "text","text": "这是什么"}, {"type": "image_url", "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}} ]}] ) print(completion.model_dump_json())
时间: 2025-07-23 22:16:15 浏览: 1
### 实现拍照、上传图片并调用阿里百炼大模型进行图片内容理解
以下是完整的 Python 代码示例,用于实现拍照功能、上传图片以及通过 `qwen-vl-plus` 或其他指定模型来解析图片内容。
#### 安装依赖库
为了完成此任务,需要安装以下 Python 库:
- OpenCV (`cv2`):用于摄像头拍摄照片。
- Requests:用于发送 HTTP 请求到阿里云 API 并获取响应数据。
可以通过运行以下命令安装所需库:
```bash
pip install opencv-python requests
```
---
#### 完整代码示例
```python
import cv2
import base64
import json
import requests
def capture_image():
""" 使用摄像头捕获一张图片 """
cap = cv2.VideoCapture(0) # 打开默认摄像头 (索引为0)
ret, frame = cap.read() # 捕获一帧图像
if not ret:
raise Exception("无法从摄像头读取图像")
image_path = "captured_image.jpg"
cv2.imwrite(image_path, frame) # 将捕获的图像保存到本地文件
cap.release()
return image_path
def encode_image_to_base64(image_path):
""" 将图片编码为 Base64 字符串 """
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return encoded_string
def call_qwen_vl_api(api_key, model_name, image_content, question="这是什么?"):
""" 调用阿里云 Qwen-VL 大模型接口进行图片内容理解 """
url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"model": model_name,
"input": {
"messages": [
{
"role": "user",
"content": [
{"image": image_content},
{"text": question}
]
}
]
}
}
response = requests.post(url, headers=headers, data=json.dumps(data))
result = response.json()
if response.status_code != 200 or "output" not in result:
error_message = result.get("error", {}).get("message", "未知错误")
raise Exception(f"API 请求失败: {error_message}")
answer = result["output"]["messages"][0]["content"]
return answer
if __name__ == "__main__":
try:
api_key = "<your-dashscope-api-key>" # 替换为您自己的 DashScope API Key
model_name = "qwen-vl-plus"
# Step 1: 拍摄图片
captured_image_path = capture_image()
# Step 2: 编码图片为 Base64 格式
encoded_image = encode_image_to_base64(captured_image_path)
# Step 3: 调用 Qwen-VL 接口分析图片内容
analysis_result = call_qwen_vl_api(
api_key=api_key,
model_name=model_name,
image_content=encoded_image
)
print("图片内容分析结果:", analysis_result)
except Exception as e:
print("发生错误:", str(e))
```
---
#### 关键说明
1. **摄像头捕捉**
上述代码中的 `capture_image()` 函数利用 OpenCV 的 `VideoCapture` 类打开设备上的摄像头,并捕获单张图片。该函数会返回存储路径以便后续处理[^1]。
2. **Base64 图片编码**
阿里云 API 支持接收 Base64 编码后的图片字符串作为输入参数之一。因此,在实际请求之前需先将图片转换成 Base64 格式的字符串[^2]。
3. **Qwen-VL Plus 模型调用**
提供了一个通用方法 `call_qwen_vl_api()` 来封装向阿里云发起 POST 请求的过程。它接受四个主要参数——您的个人 API 密钥、所选具体模型名称(例如 `"qwen-vl-plus"`)、经过编码处理过的图片数据以及可选项问题描述文字,默认设置为询问对象类别【即 “这是什么?”】[^2]。
4. 错误处理机制已内置至各模块内部以增强健壮性;当遇到任何异常状况时均能及时反馈给用户端知悉具体情况原因所在之处。
---
阅读全文