image_read.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. import base64
  3. import cv2
  4. import dashscope
  5. # 各地域配置不同,请根据实际地域修改
  6. dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"
  7. camera_id = 10 # 摄像头ID
  8. def capture_image_from_camera():
  9. cap = cv2.VideoCapture(camera_id)
  10. if not cap.isOpened():
  11. print(f"无法打开摄像头ID: {camera_id}")
  12. return None
  13. ret, frame = cap.read()
  14. cap.release()
  15. if not ret:
  16. print(f"无法捕获图像,camera_id: {camera_id}")
  17. return None
  18. _, buffer = cv2.imencode('.jpg', frame)
  19. image_base64 = base64.b64encode(buffer).decode('utf-8')
  20. return image_base64
  21. image_base64 = capture_image_from_camera()
  22. if image_base64 is None:
  23. print(f"摄像头捕获失败,camera_id: {camera_id}")
  24. exit(1)
  25. messages = [
  26. {
  27. "role": "user",
  28. "content": [
  29. {"image": f"data:image/jpeg;base64,{image_base64}"},
  30. {"text": "图中描绘的是什么景象?"}]
  31. }]
  32. response = dashscope.MultiModalConversation.call(
  33. # 若没有配置环境变量, 请用百炼API Key将下行替换为: api_key ="sk-xxx"
  34. # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
  35. api_key = os.getenv('DASHSCOPE_API_KEY'),
  36. model = 'qwen3.5-plus', # 此处以qwen3.5-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/models
  37. messages = messages
  38. )
  39. print(f'模型回复: {response.output.choices[0].message.content[0]["text"]}')