多模态 AI 系统:图像、文本与音频分析
多模态 AI 指能够理解和处理多种数据类型(文本、图像、音频、视频)的人工智能系统。GPTV、Gemini 和 Claude 3 等模型在这一领域取得了突破性进展。
多模态 AI 基础
模态类型
- 文本: 自然语言、代码、结构化数据
- 视觉: 照片、图表、截图
- 音频: 语音、音乐、环境声音
- 视频: 动态影像 + 音频的组合
为什么需要多模态?
- 人类交流本质上就是多模态的
- 单一模态会遗漏关键信息
- 能提取更丰富的语义
- 更适用于真实世界场景
视觉-语言模型
模型架构方法
1. 对比学习(CLIP 风格)
1Image Encoder → Image Embedding 2Text Encoder → Text Embedding 3Contrastive Loss: Match(image, text)
2. 生成式(GPTV 风格)
Image → Vision Encoder → Visual Tokens Visual Tokens + Text Tokens → LLM → Response
3. 交叉注意力融合
Image Features ←Cross-Attention→ Text Features
视觉编码器类型
| Encoder | Architecture | Resolution | Feature |
|---|---|---|---|
| ViT | Transformer | 224-1024 | Patch-based |
| CLIP ViT | Transformer | 336 | Contrastive |
| SigLIP | Transformer | 384 | Sigmoid loss |
| ConvNeXt | CNN | Flexible | Efficient |
图像分词(Image Tokenization)
Patch Embedding:
224×224 image → 14×14 patch grid → 196 visual tokens Each patch: 16×16 pixel → Linear projection → Embedding
可变分辨率:
1Anyres approach: 21. Divide image into tiles 32. Encode each tile separately 43. Add global thumbnail 54. Concatenate all tokens
多模态 LLM 实现
GPTV 使用示例
1from openai import OpenAI 2import base64 3 4client = OpenAI() 5 6def encode_image(image_path): 7 with open(image_path, "rb") as f: 8 return base64.b64encode(f.read()).decode('utf-8') 9 10response = client.chat.completions.create( 11 model="gpt-4-vision-preview", 12 messages=[ 13 { 14 "role": "user", 15 "content": [ 16 {"type": "text", "text": "Analyze this image"}, 17 { 18 "type": "image_url", 19 "image_url": { 20 "url": f"data:image/jpeg;base64,{encode_image('image.webp')}", 21 "detail": "high" # low, high, auto 22 } 23 } 24 ] 25 } 26 ], 27 max_tokens=1000 28)
Claude 3 Vision
1from anthropic import Anthropic 2import base64 3 4client = Anthropic() 5 6with open("image.webp", "rb") as f: 7 image_data = base64.standard_b64encode(f.read()).decode("utf-8") 8 9message = client.messages.create( 10 model="claude-3-opus-20240229", 11 max_tokens=1024, 12 messages=[ 13 { 14 "role": "user", 15 "content": [ 16 { 17 "type": "image", 18 "source": { 19 "type": "base64", 20 "media_type": "image/jpeg", 21 "data": image_data 22 } 23 }, 24 {"type": "text", "text": "What is in this image?"} 25 ] 26 } 27 ] 28) 29## 音频处理 30 31### 语音转文本(STT) 32 33**Whisper 模型:** 34```python 35from openai import OpenAI 36 37client = OpenAI() 38 39with open("audio.mp3", "rb") as audio_file: 40 transcript = client.audio.transcriptions.create( 41 model="whisper-1", 42 file=audio_file, 43 language="en" 44 ) 45 46print(transcript.text)
文本转语音(TTS)
1response = client.audio.speech.create( 2 model="tts-1-hd", 3 voice="alloy", # alloy, echo, fable, onyx, nova, shimmer 4 input="Hello, I am an AI assistant." 5) 6 7response.stream_to_file("output.mp3")
实时音频管线
1Microphone → VAD → Chunking → STT → LLM → TTS → Speaker 2 ↓ 3 Voice Activity 4 Detection
视频理解
帧采样策略
1. 均匀采样:
1def uniform_sample(video_path, num_frames=8): 2 cap = cv2.VideoCapture(video_path) 3 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) 4 indices = np.linspace(0, total_frames-1, num_frames, dtype=int) 5 6 frames = [] 7 for idx in indices: 8 cap.set(cv2.CAP_PROP_POS_FRAMES, idx) 9 ret, frame = cap.read() 10 if ret: 11 frames.append(frame) 12 13 return frames
2. 关键帧提取:
1def extract_keyframes(video_path, threshold=30): 2 # Finding keyframes with Scene change detection 3 pass
Video-LLM 管线
1Video → Frame Sampling → Per-frame Encoding → Temporal Aggregation → LLM 2 ↓ 3 Audio Extraction → STT → Text
多模态融合
早期融合
在模型输入阶段融合多模态:
[CLS] [IMG_1] ... [IMG_N] [SEP] [TXT_1] ... [TXT_M] [SEP]
后期融合
分别处理各模态并融合结果:
1Image → Image Model → Image Features ─┐ 2 ├→ Fusion Layer → Output 3Text → Text Model → Text Features ────┘
跨模态注意力
模态之间的注意力机制:
1Q = Text Features 2K, V = Image Features 3Cross_Attention(Q, K, V) = softmax(QK^T/√d)V
OCR 与文档理解
文档 AI 管线
1def process_document(image_path): 2 # 1. Layout Detection 3 layout = detect_layout(image) # Headings, paragraphs, tables 4 5 # 2. OCR 6 text_regions = ocr_extract(image) 7 8 # 3. Structure Understanding 9 structured_doc = parse_structure(layout, text_regions) 10 11 # 4. LLM Analysis 12 analysis = llm_analyze(structured_doc) 13 14 return analysis
表格提取
1response = client.chat.completions.create( 2 model="gpt-4-vision-preview", 3 messages=[{ 4 "role": "user", 5 "content": [ 6 {"type": "image_url", "image_url": {"url": table_image_url}}, 7 {"type": "text", "text": "Extract this table in JSON format"} 8 ] 9 }] 10)
企业级多模态应用
1. 文档处理
- 发票/收据 OCR
- 合同分析
- 表单数据提取
2. 视觉搜索
- 基于产品图片的搜索
- 相似图片查找
- 视觉问答
3. 内容审核
- 不当图像检测
- 品牌标识检查
- 文本 + 图像一致性
4. 客户支持
- 截图分析
- 视觉故障排查
- 语音支持
性能优化
图像预处理
1def optimize_image(image_path, max_size=1024, quality=85): 2 img = Image.open(image_path) 3 4 # Resize 5 if max(img.size) > max_size: 6 ratio = max_size / max(img.size) 7 new_size = tuple(int(d * ratio) for d in img.size) 8 img = img.resize(new_size, Image.LANCZOS) 9 10 # Compress 11 buffer = io.BytesIO() 12 img.save(buffer, format="JPEG", quality=quality) 13 14 return buffer.getvalue()
批处理
1async def batch_image_analysis(images, batch_size=5): 2 results = [] 3 for i in range(0, len(images), batch_size): 4 batch = images[i:i+batch_size] 5 tasks = [analyze_image(img) for img in batch] 6 batch_results = await asyncio.gather(*tasks) 7 results.extend(batch_results) 8 return results
成本管理
Token 计算(Vision)
1GPTV Token 成本: 2- 低细节:85 token/图片 3- 高细节:85 + 170 × tile_count 4 5示例(2048×1024,高细节): 6Tiles: ceil(2048/512) × ceil(1024/512) = 4 × 2 = 8 7Tokens: 85 + 170 × 8 = 1445 tokens
优化策略
- 调整细节级别: 非必要不要使用 "high"
- 减少图像尺寸: 可降低 token 数量
- 缓存: 避免重复分析相同图像
- 批处理: 减少 API 调用次数
结论
多模态 AI 是人工智能最接近人类理解能力的方式。图像、文本和音频模态的结合使创建更强大、更实用的 AI 应用成为可能。
在 Veni AI,我们开发多模态 AI 解决方案。如有项目需求,欢迎联系我们。
