> ## Documentation Index
> Fetch the complete documentation index at: https://docs.laozhang.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 图像与视频理解

> 使用 AI 模型进行智能图像和视频分析，支持对象识别、场景描述、文字提取、视频内容理解等功能

## 功能简介

老张API 提供强大的图像和视频理解能力，支持使用多种先进的 AI 模型对图像和视频进行深度分析和理解。图片理解可使用 OpenAI 兼容 Chat Completions；视频理解请使用 Gemini 原生 `generateContent` 协议，以确保视频帧、画面文字和音频轨道都能被模型读取。

<Note>
  **🔍 智能视觉分析**\
  支持对象识别、场景理解、文字提取、情感分析、视频内容理解等多种视觉任务，让 AI 真正"看懂"图片和视频。
</Note>

## 🌟 核心特性

* **🎯 多模型支持**：GPT-5、Gemini 2.5 Pro/Flash 等顶级视觉模型
* **📸 灵活输入**：图片支持 URL 和 Base64；视频支持 Gemini 原生 `file_data` URL 和 `inlineData` Base64
* **🎬 视频理解**：Gemini 系列支持视频内容分析和 OCR，部分模型可同时读取音频轨道
* **🌏 中文优化**：完美支持中文场景理解和文字识别
* **⚡ 快速响应**：高性能推理，秒级返回结果
* **💰 成本可控**：多种模型选择，满足不同预算需求

## 📋 支持的视觉模型

| 模型名称                   | 模型 ID               | 图片支持 | 视频支持 | 特点                 |
| ---------------------- | ------------------- | ---- | ---- | ------------------ |
| **GPT-5** ⭐            | `gpt-5`             | ✅    | ❌    | 最新模型，图片识别非常详细准确    |
| **Gemini 2.5 Pro** ⭐   | `gemini-2.5-pro`    | ✅    | ✅    | 超长上下文，支持视频分析       |
| **Gemini 2.5 Flash** ⭐ | `gemini-2.5-flash`  | ✅    | ✅    | 速度极快，适合成本敏感任务，支持视频 |
| **GPT-4.1 Mini**       | `gpt-4.1-mini`      | ✅    | ❌    | 轻量快速，成本低           |
| **Claude 3.5 Sonnet**  | `claude-3-5-sonnet` | ✅    | ❌    | 理解深入，描述准确          |

<Note>
  💡 **视频分析提示**：目前仅 Gemini 系列模型支持视频内容理解。Chat Completions 的 `video_url` / 将 MP4 填入 `image_url` 不作为视频理解推荐接入方式；请使用下方 Gemini 原生协议。
</Note>

## 🚀 快速开始

### 1. 基础示例 - 图片 URL

```python theme={null}
import requests

url = "https://api2.laozhang.ai/v1/chat/completions"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

payload = {
    "model": "gpt-4o",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "请详细描述这张图片的内容"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/image.jpg"
                    }
                }
            ]
        }
    ]
}

response = requests.post(url, headers=headers, json=payload)
result = response.json()
print(result['choices'][0]['message']['content'])
```

### 2. 本地图片示例 - Base64 编码

```python theme={null}
import base64
import requests

def image_to_base64(image_path):
    """将本地图片转换为 base64 编码"""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

# 读取本地图片
base64_image = image_to_base64("path/to/your/image.jpg")

url = "https://api2.laozhang.ai/v1/chat/completions"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

payload = {
    "model": "gemini-2.5-pro",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "分析这张图片中的所有文字内容"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}"
                    }
                }
            ]
        }
    ]
}

response = requests.post(url, headers=headers, json=payload)
print(response.json()['choices'][0]['message']['content'])
```

### 3. 高级示例 - 多图对比分析

```python theme={null}
import requests

url = "https://api2.laozhang.ai/v1/chat/completions"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

payload = {
    "model": "gpt-4o",
    "messages": [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "请对比这两张图片的差异："},
                {
                    "type": "image_url",
                    "image_url": {"url": "https://example.com/image1.jpg"}
                },
                {
                    "type": "image_url", 
                    "image_url": {"url": "https://example.com/image2.jpg"}
                }
            ]
        }
    ],
    "max_tokens": 1000
}

response = requests.post(url, headers=headers, json=payload)
print(response.json()['choices'][0]['message']['content'])
```

## 🎬 视频内容分析

### 支持的视频模型

目前**仅 Gemini 系列模型**支持视频分析。以下模型已用同一个 MP4 样本通过 `generateContent + file_data` 实测：

| 模型 ID                           | 视频输入 | 音频轨道              | 适合场景                      |
| ------------------------------- | ---- | ----------------- | ------------------------- |
| `gemini-3.5-flash`              | ✅    | 未返回 `AUDIO` token | 最新 Flash，适合快速视觉概述         |
| `gemini-3.1-pro-preview`        | ✅    | 未返回 `AUDIO` token | 预览 Pro，适合复杂视觉理解；高峰期可能返回繁忙 |
| `gemini-3.1-flash-lite`         | ✅    | 未返回 `AUDIO` token | 快速、低成本视觉分析                |
| `gemini-3.1-flash-lite-preview` | ✅    | 未返回 `AUDIO` token | 预览轻量模型，行为与正式 Lite 接近      |
| `gemini-3-flash-preview`        | ✅    | 未返回 `AUDIO` token | 快速视频概述和 OCR               |
| `gemini-2.5-pro`                | ✅    | ✅                 | 需要同时理解画面和旁白时优先测试          |
| `gemini-2.5-flash`              | ✅    | ✅                 | 成本、速度和音轨理解的平衡选择           |
| `gemini-2.5-flash-lite`         | ✅    | ✅                 | 低成本批量视频分析                 |
| `gemini-2.5-flash-nothinking`   | ✅    | ✅                 | 需要关闭深度推理风格时可评估            |

<Note>
  `gemini-3-pro-image`、`gemini-3.1-flash-image` 等 `*-image` 模型是图像生成/编辑模型，不作为视频理解默认模型。是否读取音轨请以返回的 `usageMetadata.promptTokensDetails` 是否包含 `AUDIO` 为准。
</Note>

### 已验证的协议

视频理解请走 Gemini 原生接口：

* `POST https://api2.laozhang.ai/v1beta/models/{model}:generateContent`
* 认证方式：`x-goog-api-key: YOUR_API_KEY` 或 `Authorization: Bearer YOUR_API_KEY`
* 远程视频：使用 `file_data.mime_type` + `file_data.file_uri`
* 本地视频：使用 `inlineData.mimeType` + `inlineData.data`

<Warning>
  不建议用 `/v1/chat/completions` 传视频。实测 `video_url` 请求会作为文本 URL 处理，模型可能明确回复无法访问视频；把 MP4 放进 `image_url` 会返回请求错误。
</Warning>

### 1. 远程视频 URL 分析

`maxOutputTokens` 可以不设置。需要限制输出时，请不要设得过小；`gemini-2.5-pro` 会先消耗推理 token，输出预算太低可能导致空响应或回答不完整。

```bash theme={null}
curl -sS "https://api2.laozhang.ai/v1beta/models/gemini-2.5-pro:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "file_data": {
              "mime_type": "video/mp4",
              "file_uri": "https://example.com/video.mp4"
            }
          },
          {
            "text": "请基于视频内容回答，不要根据文件名或链接猜测。用中文输出：1. 一句话概述；2. 分时间段说明发生了什么；3. 画面主体、动作、风格、可见文字和音频内容。"
          }
        ]
      }
    ],
    "generationConfig": {
      "temperature": 0
    }
  }'
```

提取返回文本：

```bash theme={null}
curl -sS "https://api2.laozhang.ai/v1beta/models/gemini-2.5-pro:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "file_data": {
              "mime_type": "video/mp4",
              "file_uri": "https://example.com/video.mp4"
            }
          },
          {
            "text": "总结这个视频，并列出可见文字和音频内容。"
          }
        ]
      }
    ]
  }' | jq -r '.candidates[0].content.parts[]?.text'
```

### 2. Python 示例

```python theme={null}
import requests

api_key = "YOUR_API_KEY"
model = "gemini-2.5-pro"

payload = {
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "file_data": {
                        "mime_type": "video/mp4",
                        "file_uri": "https://example.com/video.mp4",
                    }
                },
                {
                    "text": "请按时间线概述视频内容，并提取画面文字和音频信息。"
                },
            ],
        }
    ],
    "generationConfig": {"temperature": 0},
}

response = requests.post(
    f"https://api2.laozhang.ai/v1beta/models/{model}:generateContent",
    headers={
        "x-goog-api-key": api_key,
        "Content-Type": "application/json",
    },
    json=payload,
    timeout=180,
)

result = response.json()
answer = "\n".join(
    part.get("text", "")
    for part in result["candidates"][0]["content"]["parts"]
    if "text" in part
)
print(answer)
print(result.get("usageMetadata"))
```

### 3. 本地视频 Base64 上传

本地视频建议优先上传到可访问的 HTTPS 地址，再使用 `file_data`。如果必须直接传文件，可以使用 Base64；请求体会比原文件大约增加 33%。

```python theme={null}
import base64
import requests

api_key = "YOUR_API_KEY"
model = "gemini-2.5-pro"

with open("video.mp4", "rb") as video_file:
    video_b64 = base64.b64encode(video_file.read()).decode("utf-8")

payload = {
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "inlineData": {
                        "mimeType": "video/mp4",
                        "data": video_b64,
                    }
                },
                {"text": "请详细描述这个视频的内容，并提取可见文字。"},
            ],
        }
    ],
    "generationConfig": {"temperature": 0},
}

response = requests.post(
    f"https://api2.laozhang.ai/v1beta/models/{model}:generateContent",
    headers={
        "x-goog-api-key": api_key,
        "Content-Type": "application/json",
    },
    json=payload,
    timeout=240,
)

print(response.json()["candidates"][0]["content"]["parts"][0]["text"])
```

### 4. 返回结构

成功响应包含 `candidates`、`usageMetadata`、`modelVersion` 和 `responseId`。视频被真实读取时，`usageMetadata.promptTokensDetails` 中会出现 `VIDEO`，如果视频有音轨，还会出现 `AUDIO`：

```json theme={null}
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "该视频展示了..."
          }
        ]
      }
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 4756,
    "candidatesTokenCount": 484,
    "totalTokenCount": 6309,
    "thoughtsTokenCount": 1069,
    "promptTokensDetails": [
      { "modality": "TEXT", "tokenCount": 64 },
      { "modality": "VIDEO", "tokenCount": 4208 },
      { "modality": "AUDIO", "tokenCount": 484 }
    ]
  },
  "modelVersion": "gemini-2.5-pro"
}
```

### 5. 视频 + 图片混合分析

Gemini 原生协议支持在同一个 `parts` 数组里混合视频、图片和文本。图片可以使用 `file_data` URL 或 `inlineData` Base64。

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "file_data": {
            "mime_type": "video/mp4",
            "file_uri": "https://example.com/video.mp4"
          }
        },
        {
          "file_data": {
            "mime_type": "image/jpeg",
            "file_uri": "https://example.com/reference.jpg"
          }
        },
        {
          "text": "对比视频内容和参考图，说明主体、风格和可见文字差异。"
        }
      ]
    }
  ]
}
```

**MIME 类型说明**：

不同视频格式需要使用对应的 MIME 类型：

* **MP4**：`video/mp4`
* **WebM**：`video/webm`
* **MOV**：`video/quicktime`
* **AVI**：`video/x-msvideo`

<Tip>
  💡 **最佳实践**：Base64 编码会增加约 33% 的数据量。对于大视频文件（>10MB），建议优先使用 `file_data` URL 方式。小视频文件可以使用 `inlineData`，但仍建议设置较长的请求超时。
</Tip>

### 视频分析最佳实践

1. **文件大小**：建议单个视频 ≤20 MB，超大视频可能导致处理时间过长
2. **视频格式**：支持 MP4、WebM、MOV、AVI 等主流格式
3. **视频时长**：短视频（\< 5 分钟）效果最佳，超长视频建议分段处理
4. **分辨率**：高分辨率视频识别效果更好，但会增加处理时间
5. **提示词优化**：明确指出需要分析的内容（如"分析人物动作"、"提取对话内容"等）
6. **输出长度**：`maxOutputTokens` 可以不设置；如果设置，避免过小，否则 Gemini 2.5 Pro 的推理 token 可能先耗尽输出预算

### 视频分析应用场景

* **📹 内容审核**：自动识别视频中的不当内容
* **🎓 教学视频分析**：提取关键知识点和字幕
* **🛡️ 监控视频理解**：异常行为检测和事件识别
* **🎬 广告素材分析**：评估创意元素和情感传递效果
* **📊 体育赛事分析**：识别运动员动作和比赛关键时刻

<Warning>
  ⚠️ **注意事项**：

  * 视频处理时间通常比图片长（取决于视频长度和复杂度）
  * 如需控制输出长度，请使用 `generationConfig.maxOutputTokens`
  * 对于隐私敏感的视频内容，请注意数据安全
</Warning>

## 🎯 常见应用场景

### 1. 商品识别与分析

```python theme={null}
prompt = """
请分析这张商品图片，包括：
1. 商品类型和品牌
2. 主要特征和卖点
3. 适合的目标用户
4. 建议的营销文案
"""
```

### 2. 文档 OCR 识别

```python theme={null}
prompt = """
请提取图片中的所有文字内容，并按照原始格式整理输出。
如果有表格，请用 Markdown 表格格式呈现。
"""
```

### 3. 医学影像辅助分析

```python theme={null}
prompt = """
这是一张医学影像图片，请：
1. 描述图像的基本信息（如成像类型、部位等）
2. 标注可见的解剖结构
3. 注意：仅供参考，不作为诊断依据
"""
```

### 4. 安全监控场景分析

```python theme={null}
prompt = """
分析监控画面，识别：
1. 场景中的人数和位置
2. 是否有异常行为
3. 环境安全隐患
4. 时间戳信息（如果可见）
"""
```

## 💡 最佳实践

### 图片预处理建议

1. **格式支持**：JPEG、PNG、GIF、WebP 等主流格式
2. **大小限制**：建议单张图片不超过 20MB
3. **分辨率**：高分辨率图片会获得更好的识别效果
4. **压缩优化**：适度压缩以提高传输速度

### 提示词优化

```python theme={null}
# ❌ 不推荐：模糊的提示
prompt = "看看这是什么"

# ✅ 推荐：具体明确的提示
prompt = """
请从以下几个方面分析这张图片：
1. 主要对象：识别图片中的主要物体或人物
2. 场景环境：描述拍摄地点和环境特征
3. 色彩构图：分析配色方案和构图特点
4. 情感氛围：图片传达的情绪或氛围
5. 可能用途：这张图片适合用于什么场景
"""
```

### 错误处理

```python theme={null}
import requests
from requests.exceptions import RequestException

def analyze_image_with_retry(image_url, prompt, max_retries=3):
    """带重试机制的图像分析函数"""
    for attempt in range(max_retries):
        try:
            response = requests.post(
                "https://api2.laozhang.ai/v1/chat/completions",
                headers={
                    "Authorization": f"Bearer {API_KEY}",
                    "Content-Type": "application/json"
                },
                json={
                    "model": "gpt-4o",
                    "messages": [{
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {"type": "image_url", "image_url": {"url": image_url}}
                        ]
                    }]
                },
                timeout=30
            )
            
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 429:
                print(f"速率限制，等待后重试... (尝试 {attempt + 1}/{max_retries})")
                time.sleep(2 ** attempt)  # 指数退避
            else:
                print(f"错误: {response.status_code} - {response.text}")
                
        except RequestException as e:
            print(f"请求异常: {e}")
            
    return None
```

## 🔧 高级功能

### 1. 流式输出

对于长篇分析，可以使用流式输出获得更好的用户体验：

```python theme={null}
payload = {
    "model": "gpt-4o",
    "messages": [...],
    "stream": True
}

response = requests.post(url, headers=headers, json=payload, stream=True)
for line in response.iter_lines():
    if line:
        print(line.decode('utf-8'))
```

### 2. 多轮对话

保持上下文进行深入分析：

```python theme={null}
messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "这是什么动物？"},
            {"type": "image_url", "image_url": {"url": "animal.jpg"}}
        ]
    },
    {
        "role": "assistant",
        "content": "这是一只金毛寻回犬。"
    },
    {
        "role": "user",
        "content": [{"type": "text", "text": "它看起来多大了？健康状况如何？"}]
    }
]
```

### 3. 结合函数调用

```python theme={null}
tools = [
    {
        "type": "function",
        "function": {
            "name": "save_image_analysis",
            "description": "保存图像分析结果到数据库",
            "parameters": {
                "type": "object",
                "properties": {
                    "objects": {"type": "array", "items": {"type": "string"}},
                    "scene": {"type": "string"},
                    "text_content": {"type": "string"}
                }
            }
        }
    }
]

payload = {
    "model": "gpt-4o",
    "messages": messages,
    "tools": tools,
    "tool_choice": "auto"
}
```

## 📊 性能对比

| 模型               | 图片支持 | 视频支持 | 响应速度  | 识别准确度 | 价格     |
| ---------------- | ---- | ---- | ----- | ----- | ------ |
| GPT-5            | ✅    | ❌    | ⭐⭐⭐⭐  | ⭐⭐⭐⭐⭐ | \$\$\$ |
| Gemini 2.5 Pro   | ✅    | ✅    | ⭐⭐⭐⭐  | ⭐⭐⭐⭐⭐ | \$\$   |
| Gemini 2.5 Flash | ✅    | ✅    | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐  | \$     |
| GPT-4.1 Mini     | ✅    | ❌    | ⭐⭐⭐⭐⭐ | ⭐⭐⭐   | \$     |

## 🚨 注意事项

1. **隐私保护**：不要上传包含敏感信息的图片和视频
2. **合规使用**：遵守相关法律法规，不用于非法用途
3. **结果验证**：AI 分析结果仅供参考，重要决策需人工复核
4. **成本控制**：合理选择模型，避免不必要的开销
5. **视频限制**：视频分析仅支持 Gemini 系列，其他模型暂不支持

## 🔗 相关资源

* [API 定价说明](https://api2.laozhang.ai/account/pricing)
* [Chat Completions API](/api-reference/chat-completions) - 了解更多关于对话 API 的信息

<Note>
  💡 **小贴士**：建议先使用 Gemini 2.5 Flash 或 GPT-4.1 Mini 进行测试，确认效果后再使用高级模型进行生产部署。
</Note>
