マルチモーダル AI システム:画像・テキスト・音声解析
マルチモーダル AI とは、複数のデータタイプ(テキスト、画像、音声、動画)を理解・処理できる人工知能システムを指します。GPTV、Gemini、Claude 3 などのモデルは、この分野で新たな地平を切り開きました。
マルチモーダル AI の基礎
モダリティの種類
- Text: 自然言語、コード、構造化データ
- Vision: 写真、図表、スクリーンショット
- Audio: 音声、音楽、環境音
- Video: 動画(映像+音声)
なぜマルチモーダルなのか?
- 人間のコミュニケーションは本質的にマルチモーダルである
- 単一モダリティでは欠落する文脈情報がある
- より豊かな意味抽出が可能
- 実世界のアプリケーションに適している
ビジョン・ランゲージモデル
アーキテクチャのアプローチ
1. Contrastive Learning(CLIP スタイル)
1Image Encoder → Image Embedding 2Text Encoder → Text Embedding 3Contrastive Loss: Match(image, text)
2. Generative(GPTV スタイル)
Image → Vision Encoder → Visual Tokens Visual Tokens + Text Tokens → LLM → Response
3. Cross-Attention Fusion
Image Features ←Cross-Attention→ Text Features
Vision Encoder の種類
| Encoder | Architecture | Resolution | Feature |
|---|---|---|---|
| ViT | Transformer | 224-1024 | Patch-based |
| CLIP ViT | Transformer | 336 | Contrastive |
| SigLIP | Transformer | 384 | Sigmoid loss |
| ConvNeXt | CNN | Flexible | Efficient |
画像トークン化
Patch Embedding:
224×224 image → 14×14 patch grid → 196 visual tokens Each patch: 16×16 pixel → Linear projection → Embedding
Variable Resolution:
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
モダリティ融合
早期融合(Early Fusion)
モダリティをモデル入力段階で統合:
[CLS] [IMG_1] ... [IMG_N] [SEP] [TXT_1] ... [TXT_M] [SEP]
後期融合(Late Fusion)
各モダリティを別々に処理し、結果を統合:
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 とドキュメント理解
Document 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. ビジュアル検索
- 商品画像からの検索
- 類似画像検索
- 画像によるQ&A
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
コスト管理
トークン計算(Vision)
1GPTV Token Cost: 2- Low detail: 85 token/image 3- High detail: 85 + 170 × tile_count 4 5Example (2048×1024, high): 6Tiles: ceil(2048/512) × ceil(1024/512) = 4 × 2 = 8 7Tokens: 85 + 170 × 8 = 1445 tokens
最適化戦略
- 詳細レベルを調整: 必要な場合以外は "high" を使用しない
- 画像サイズを縮小: トークン数を削減
- キャッシング: 同じ画像を再解析しない
- バッチ処理: API 呼び出し回数を削減
結論
マルチモーダル AI は、人間に近い理解能力を持つ人工知能に最も近いアプローチです。画像・テキスト・音声を組み合わせることで、より強力で有用な AI アプリケーションを実現できます。
Veni AI では、マルチモーダル AI ソリューションを開発しています。プロジェクトについてぜひご相談ください。
