コンピュータビジョン AI
人間が得る情報の約80%は視覚から来ている。
写真を見れば、そこに何人いるか、彼らが何をしているか、背景が室内か屋外かをすぐに認識できる。
しかしコンピュータにとって、この写真はただの数字の集まりにすぎない。各ピクセルは赤・緑・青の3つの値で表されるだけで、それ以上でも以下でもない。
コンピュータビジョン(Computer Vision、略称CV)は、コンピュータに画像を理解させる技術である。
スマートフォンの顔認証によるロック解除から、自動運転の道路状況認識、さらには医用画像の病変解析まで、コンピュータビジョンはすでに至る所で使われている。
このモジュールでは、基本的な畳み込みニューラルネットワークから最新の視覚言語モデルまでを学ぶことができる。
学習パス:畳み込みニューラルネットワーク → Vision Transformer → 物体検出 → 画像セグメンテーション → 拡散モデル → CLIP → 視覚言語モデル。各ステップには実行可能なコード例が用意されている。
畳み込みニューラルネットワーク(CNN)
CNNはコンピュータビジョンの基盤技術であり、人間の視覚野の働き方を模倣し、局所受容野を通じて画像特徴を抽出する。
畳み込み演算の原理
畳み込みの核心的な考え方は次の通り:小さなスライディングウィンドウ(畳み込みカーネル)を画像上で走査し、局所的な特徴を抽出する。
例えば、3×3の畳み込みカーネルは、毎回画像上の9個のピクセルを参照し、それらの加重和を計算して1つの出力値を得る。
このプロセスを繰り返し、畳み込みカーネルが画像上を左から右へ、上から下へスライドし、最終的に「特徴マップ」を生成する。
実例
# NumPyを使って最もシンプルな畳み込み演算を実装
# 畳み込みがエッジ特徴を抽出する仕組みをデモ
# ============================================
import numpy as np
def simple_convolution(image: np.ndarray, kernel: np.ndarray) -> np.ndarray:
"""
最も基本的な2D畳み込み演算を実装(paddingとstrideは含まない)
パラメータ:
image: 入力画像 (H, W)、単チャネルのグレースケール画像
kernel: 畳み込みカーネル (kH, kW)
戻り値:
畳み込み後の特徴マップ
"""
# 画像と畳み込みカーネルのサイズを取得
img_h, img_w = image.shape
kernel_h, kernel_w = kernel.shape
# 出力特徴マップのサイズを計算
# 出力サイズ = 入力サイズ - 畳み込みカーネルサイズ + 1
out_h = img_h - kernel_h + 1
out_w = img_w - kernel_w + 1
# 出力特徴マップを初期化
output = np.zeros((out_h, out_w))
# 畳み込みカーネルをスライドさせて計算
for i in range(out_h):
for j in range(out_w):
# 画像から畳み込みカーネルに対応する局所領域を取り出す
region = image[i:i+kernel_h, j:j+kernel_w]
# 対応する要素を乗算して合計する(これが畳み込み演算)
output[i, j] = np.sum(region * kernel)
return output
# シンプルなテスト画像を作成:中央が白い四角形、周囲は黒
# 形状:8×8のグレースケール画像
test_image = np.array([
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
])
print("元の画像:")
print(test_image)
# エッジ検出用の畳み込みカーネルを定義(Sobelオペレータの簡易版)
# この畳み込みカーネルは垂直エッジを検出できる
edge_kernel = np.array([
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1],
])
# 畳み込みを実行
feature_map = simple_convolution(test_image, edge_kernel)
print("\n畳み込み後の特徴マップ(垂直エッジを検出):")
print(np.round(feature_map, 2))
畳み込み演算の重要なポイント:畳み込みカーネルのパラメータは学習によって得られるものであり、人手で設計されるものではない。
トレーニング中に、モデルは畳み込みカーネルの値を自動的に調整し、タスクに有用な特徴を抽出できるようにする。
プーリング(Pooling)
プーリングの役割は、特徴マップのサイズを圧縮して計算量を減らしつつ、重要な特徴をそのまま保つことである。
最も一般的なのは最大プーリング(Max Pooling):特徴マップを複数の小さなブロックに分割し、各ブロックで最大値のみを保持する。
実例
# 最大プーリング演算を実装
# ============================================
def max_pooling(feature_map: np.ndarray, pool_size: int = 2) -> np.ndarray:
"""
最大プーリング演算を実装
パラメータ:
feature_map: 入力特徴マップ (H, W)
pool_size: プーリングウィンドウサイズ、デフォルトは2×2
戻り値:
プーリング後の特徴マップ
"""
h, w = feature_map.shape
# 出力サイズを計算
out_h = h // pool_size
out_w = w // pool_size
output = np.zeros((out_h, out_w))
for i in range(out_h):
for j in range(out_w):
# プーリングウィンドウ領域を取り出す
region = feature_map[
i*pool_size:(i+1)*pool_size,
j*pool_size:(j+1)*pool_size
]
# 最大値を取得
output[i, j] = np.max(region)
return output
# 先ほどの特徴マップでプーリングを実行
print("プーリング前の特徴マップ:")
print(feature_map)
pooled = max_pooling(feature_map, pool_size=2)
print("\n2×2 最大プーリング後の特徴マップ:")
print(pooled)
代表的なアーキテクチャ比較
CNNの発展史にはいくつかの画期的なアーキテクチャがあり、それぞれ異なる時代の設計思想を代表している。
| アーキテクチャ | 年 | 主要な革新 | 特徴 |
|---|---|---|---|
| AlexNet | 2012 | ReLU活性化、Dropout、データ拡張 | 深層学習時代の先駆者であり、初めてImageNetで従来手法を大幅に上回った |
| VGG | 2014 | 3×3の小さな畳み込みカーネルに統一 | 構造が簡潔で洗練されており、理解と実装が容易 |
| ResNet | 2015 | 残差接続(Skip Connection) | 深層ネットワークの勾配消失問題を解決し、ネットワークを100層以上にできる |
| EfficientNet | 2019 | 複合スケーリング手法 | 深さ、幅、解像度を同時にスケーリングし、パラメータ効率が非常に高い |
残差接続(Skip Connection)
ResNetの主要な革新は残差接続であり、「ネットワークが深くなるほど学習が難しくなる」という問題を解決した。
従来のネットワーク層の学習目標は、入力xから出力yへのマッピングを直接学習することである。
残差ネットワークの学習目標は:出力yと入力xの差(残差)を学習する。
数式で表すと:y = F(x) + x、ここでF(x)が学習すべき残差である。
残差接続の直感的理解:ネットワークに「現在の状態からどれだけ修正するか」を学習させる方が、「ゼロから完全なマッピングを学習する」よりもはるかに容易である。
実例
# PyTorchを使って完全なCNN画像分類器を実装
# 畳み込み、プーリング、残差接続を含む
# ============================================
import torch
import torch.nn as nn
import torch.nn.functional as F
class ResidualBlock(nn.Module):
"""シンプルな残差ブロック"""
def __init__(self, in_channels: int, out_channels: int, stride: int = 1):
super().__init__()
# 最初の畳み込み層
self.conv1 = nn.Conv2d(
in_channels, out_channels,
kernel_size=3, stride=stride, padding=1, bias=False
)
self.bn1 = nn.BatchNorm2d(out_channels)
# 2番目の畳み込み層
self.conv2 = nn.Conv2d(
out_channels, out_channels,
kernel_size=3, stride=1, padding=1, bias=False
)
self.bn2 = nn.BatchNorm2d(out_channels)
# ショートカット接続(次元の変化に合わせるため)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(
in_channels, out_channels,
kernel_size=1, stride=stride, bias=False
),
nn.BatchNorm2d(out_channels)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# メインパス:畳み込み → BN → ReLU → 畳み込み → BN
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
# 残差接続:入力(または次元変換後の入力)を加算
out += self.shortcut(x)
# 最後のReLU
out = F.relu(out)
return out
class SimpleCNN(nn.Module):
"""画像分類用のシンプルなCNN(残差接続付き)"""
def __init__(self, num_classes: int = 10):
super().__init__()
# 初期畳み込み層
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(32)
# 残差層
self.layer1 = ResidualBlock(32, 32)
self.layer2 = ResidualBlock(32, 64, stride=2)
self.layer3 = ResidualBlock(64, 64)
# グローバル平均プーリング
self.global_pool = nn.AdaptiveAvgPool2d((1, 1))
# 分類ヘッド
self.fc = nn.Linear(64, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x の形状: (batch_size, 3, 32, 32)
x = F.relu(self.bn1(self.conv1(x)))
x = self.layer1(x) # (batch_size, 32, 32, 32)
x = self.layer2(x) # (batch_size, 64, 16, 16)
x = self.layer3(x) # (batch_size, 64, 16, 16)
x = self.global_pool(x) # (batch_size, 64, 1, 1)
x = x.view(x.size(0), -1) # (batch_size, 64)
x = self.fc(x) # (batch_size, num_classes)
return x
# モデルを作成してテスト
model = SimpleCNN(num_classes=10)
print("モデル構造:")
print(model)
# 順伝播をテスト
# ダミーのバッチを作成:4枚の画像、各3×32×32(RGB 32×32)
test_input = torch.randn(4, 3, 32, 32)
test_output = model(test_input)
print(f"\n入力形状: {test_input.shape}")
print(f"出力形状: {test_output.shape} (batch_size, num_classes)")
Vision Transformer(ViT)
2020年、Googleは論文「An Image is Worth 16x16 Words」を発表し、Transformerアーキテクチャを言語分野から視覚分野へ移しました。
画像パッチ化(Patch Embedding)
Transformerはシーケンスデータを処理しますが、画像は2Dのグリッドデータです。
ViTの解決策は非常にシンプルです:画像を小さなブロックに切り分け、各ブロックを1つの単語(トークン)として扱います。。
例えば、224×224の画像を16×16のパッチに切り分けると、14×14 = 196個のパッチが得られます。
各パッチを1次元ベクトルにフラット化し、線形層でembeddingに投影すれば、Transformerに入力できます。
実例
# Patch Embeddingを実装(画像パッチ分割)
# ============================================
class PatchEmbedding(nn.Module):
"""
画像をパッチに分割して埋め込む
パラメータ:
img_size: 入力画像サイズ(正方形)
patch_size: 各パッチのサイズ(正方形)
in_channels: 入力チャンネル数(RGBは3)
embed_dim: 出力埋め込み次元
"""
def __init__(
self,
img_size: int = 224,
patch_size: int = 16,
in_channels: int = 3,
embed_dim: int = 768
):
super().__init__()
self.img_size = img_size
self.patch_size = patch_size
# パッチ数を計算:(224/16)^2 = 14^2 = 196
self.num_patches = (img_size // patch_size) ** 2
# 畳み込みでパッチ分割と埋め込みを実装
# これは次と等価:パッチ分割 → フラット化 → 線形投影
self.proj = nn.Conv2d(
in_channels, embed_dim,
kernel_size=patch_size, stride=patch_size
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x の形状: (batch_size, in_channels, img_size, img_size)
x = self.proj(x) # (batch_size, embed_dim, num_patches^0.5, num_patches^0.5)
x = x.flatten(2) # (batch_size, embed_dim, num_patches)
x = x.transpose(1, 2) # (batch_size, num_patches, embed_dim)
return x
# Patch Embeddingをテスト
patch_embed = PatchEmbedding(img_size=224, patch_size=16, embed_dim=768)
test_image = torch.randn(1, 3, 224, 224) # 224×224 の RGB 画像 1 枚
patches = patch_embed(test_image)
print(f"入力画像の形状: {test_image.shape}")
print(f"パッチ系列の形状: {patches.shape} (batch_size, num_patches, embed_dim)")
ViT 全体アーキテクチャ
ViTの完全なアーキテクチャには、class tokenと位置エンコーディングも必要です。
class tokenは学習可能なベクトルで、その役割はすべてのパッチの情報を「集約」することです。
位置エンコーディングも学習可能で、モデルに「各パッチが画像のどこにあるか」を伝えます。
実例
# 簡易版Vision Transformerを実装
# ============================================
class MultiHeadAttention(nn.Module):
"""マルチヘッド自己注意"""
def __init__(self, dim: int, num_heads: int):
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
assert self.head_dim * num_heads == dim, "次元はヘッド数で割り切れる必要があります"
# Q、K、V 射影行列
self.qkv = nn.Linear(dim, dim * 3)
# 出力投影
self.proj = nn.Linear(dim, dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
batch_size, seq_len, dim = x.shape
# Q、K、Vを計算
qkv = self.qkv(x) # (batch_size, seq_len, dim*3)
qkv = qkv.reshape(
batch_size, seq_len, 3, self.num_heads, self.head_dim
) # (batch_size, seq_len, 3, num_heads, head_dim)
q, k, v = qkv.unbind(2) # 各形状: (batch_size, seq_len, num_heads, head_dim)
# アテンション計算のために順序を調整
q = q.transpose(1, 2) # (batch_size, num_heads, seq_len, head_dim)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
# アテンションスコアを計算
attention = q @ k.transpose(-2, -1) / (self.head_dim ** 0.5)
attention = attention.softmax(dim=-1)
# 値を集約
out = attention @ v # (batch_size, num_heads, seq_len, head_dim)
out = out.transpose(1, 2) # (batch_size, seq_len, num_heads, head_dim)
out = out.flatten(2) # (batch_size, seq_len, dim)
# 出力投影
out = self.proj(out)
return out
class TransformerBlock(nn.Module):
"""Transformerブロック"""
def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = MultiHeadAttention(dim, num_heads)
self.norm2 = nn.LayerNorm(dim)
# MLP
mlp_hidden = int(dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(dim, mlp_hidden),
nn.GELU(),
nn.Linear(mlp_hidden, dim)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# 残差接続1
x = x + self.attn(self.norm1(x))
# 残差接続2
x = x + self.mlp(self.norm2(x))
return x
class SimpleViT(nn.Module):
"""簡易版Vision Transformer"""
def __init__(
self,
img_size: int = 224,
patch_size: int = 16,
in_channels: int = 3,
num_classes: int = 10,
embed_dim: int = 192,
depth: int = 6,
num_heads: int = 6
):
super().__init__()
# Patch埋め込み
self.patch_embed = PatchEmbedding(
img_size, patch_size, in_channels, embed_dim
)
num_patches = self.patch_embed.num_patches
# Class token
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
# 位置エンコーディング
self.pos_embed = nn.Parameter(
torch.zeros(1, num_patches + 1, embed_dim)
)
# Transformer層
self.blocks = nn.ModuleList([
TransformerBlock(embed_dim, num_heads)
for _ in range(depth)
])
# 最後のLayerNormと分類ヘッド
self.norm = nn.LayerNorm(embed_dim)
self.head = nn.Linear(embed_dim, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
batch_size = x.shape[0]
# Patch埋め込み
x = self.patch_embed(x) # (batch_size, num_patches, embed_dim)
# class tokenを追加
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
x = torch.cat((cls_tokens, x), dim=1) # (batch_size, 1+num_patches, embed_dim)
# 位置エンコーディングを追加
x = x + self.pos_embed
# Transformer層を通過
for block in self.blocks:
x = block(x)
# class tokenのみで分類
x = self.norm(x)
cls_output = x[:, 0] # 最初の位置(class token)を取得
x = self.head(cls_output)
return x
# ViTモデルを作成してテスト
vit = SimpleViT(
img_size=32, # テストしやすいように小さめの画像を使用
patch_size=8, # 8×8のパッチ
embed_dim=128,
depth=4,
num_heads=4,
num_classes=10
)
print("簡易版ViTの構造:")
print(vit)
test_input = torch.randn(2, 3, 32, 32) # 32×32の画像2枚
test_output = vit(test_input)
print(f"\n入力形状: {test_input.shape}")
print(f"出力形状: {test_output.shape}")
CNN vs ViT 比較
2つのアーキテクチャにはそれぞれ一長一短があり、どちらを選ぶかは具体的なシナリオ次第です。
| 特性 | CNN | ViT |
|---|---|---|
| 帰納バイアス | 強い(局所性、並進不変性) | 弱い(データから学習) |
| データ要件 | 小データでも機能する | 大量のデータが必要で、その利点を発揮する |
| 計算効率 | 通常は高速で、ハードウェア最適化が成熟している | パラメータ数が多く、計算集約的 |
| 解釈可能性 | 畳み込みカーネルを可視化しやすい | アテンションマップは解釈できるが、全体は難しい |
| 長距離依存 | 複数の層を重ねて初めて構築できる | 生得的に大域的な受容野をサポート |
| 適用シナリオ | データ量が限られ、リアルタイム性の要求が高い | 大規模データセット、複雑な視覚タスク |
経験則:データ量が少ない場合はCNN(ResNet、EfficientNet)を使用し、データ量が数百万以上ならViTを検討できます。現在は両者の利点を組み合わせたハイブリッドアーキテクチャ(ConvNeXtなど)もあります。
物体検出
画像分類は「この画像には何があるか」に答え、物体検出は「この画像には何があり、それらはそれぞれどこにあるか」に答えます。
物体検出の出力は一連のバウンディングボックス(Bounding Box)で、各ボックスは物体カテゴリに対応します。
2段階検出:R-CNN シリーズ
二段階検出の考え方は次のとおりです:まず物体が存在する可能性のある領域を見つけ、次にこれらの領域を分類します。。
第一段階:候補領域(Region Proposal)を生成します。これは「ここに何かあるかも」というボックスが数百個になることもあります。
第二段階:各候補領域から特徴を抽出し、物体の種類を判断するとともに、ボックスの位置を調整します。
R-CNNシリーズの進化:
| モデル | 主な改良点 | 速度 |
|---|---|---|
| R-CNN | CNNで従来の特徴を置き換え | 遅い(1枚につき数十秒) |
| Fast R-CNN | ROI Pooling、特徴計算の共有 | 中程度(1枚につき数秒) |
| Faster R-CNN | RPN(Region Proposal Network) | 速い(1枚につき数百ミリ秒) |
| Mask R-CNN | セグメンテーションブランチを追加 | 中 |
1段階検出:YOLO シリーズ
一段階検出の考え方は次のとおりです:画像上で直接高密度に予測し、候補領域を別途生成しません。。
YOLO(You Only Look Once)は一段階検出の代表格であり、速度が非常に速く、リアルタイムアプリケーションに適しています。
YOLOは画像をS×Sのグリッドに分割し、各グリッドは中心点がそのグリッド内にある物体を予測します。
各グリッドは、B個のバウンディングボックス(信頼度含む)とC個のクラス確率を予測します。
エンドツーエンド検出:DETR
DETR(DEtection TRansformer)はFacebook AIが提案した新しいパラダイムで、Transformerを使って物体検出を直接的なシーケンス予測問題に変えます。
その最大の特徴は、非最大値抑制(NMS)が不要で、アンカーボックス(Anchor)も不要であり、出力がそのまま最終結果になることです。
実践:YOLOv11 物体検出
ここではUltralytics YOLOv11を使って、完全な物体検出の例を実装します。
実例
# YOLOv11物体検出の実践
# モデル読み込み、検出、可視化を含む
# ============================================
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
class SimpleYOLO:
"""簡易版YOLOデモ(事前学習モデルを使用)"""
def __init__(self, model_name: str = "yolo11n.pt"):
"""
YOLOモデルを初期化
パラメータ:
model_name: モデル名。yolo11n.pt(nano、小)、yolo11s.pt(small)など
"""
self.model_name = model_name
self.model = None
# COCOデータセットの80クラス
self.coco_names = [
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',
'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',
'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',
'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# 各クラスの色
self.colors = np.random.randint(0, 255, (80, 3))
def load_model(self):
"""事前学習モデルを読み込む(ここでは概念をデモするためのシミュレーション実装)"""
print(f"モデル {self.model_name} を読み込み中...")
print("ヒント:実際に使用する場合はultralyticsをインストールして次のように呼び出します:")
print(" from ultralytics import YOLO")
print(" model = YOLO('yolo11n.pt')")
self.model = "pretrained_model_loaded"
print("モデルの読み込みが完了しました!")
return self
def predict_dummy(self, image: np.ndarray) -> list:
"""
検出結果のシミュレーション(デモ用)
実際の使用時は model(image) を呼び出します
戻り値:
検出結果のリスト。各要素は辞書です:
{'bbox': [x1, y1, x2, y2], 'class_id': int, 'score': float, 'class_name': str}
"""
# ここではいくつかの物体を検出したとシミュレーション
h, w = image.shape[:2]
dummy_results = [
{'bbox': [w*0.1, h*0.2, w*0.3, h*0.6], 'class_id': 0, 'score': 0.92, 'class_name': 'person'},
{'bbox': [w*0.35, h*0.4, w*0.7, h*0.8], 'class_id': 2, 'score': 0.85, 'class_name': 'car'},
{'bbox': [w*0.75, h*0.3, w*0.9, h*0.55], 'class_id': 16, 'score': 0.78, 'class_name': 'dog'},
]
return dummy_results
def visualize(self, image: np.ndarray, results: list) -> np.ndarray:
"""
画像上に検出ボックスとラベルを描画
パラメータ:
) # 1 = 前景, 0 = 背景
results: 検出結果リスト
戻り値:
アノテーション後の画像
"""
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
draw = ImageDraw.Draw(image)
for result in results:
bbox = result['bbox']
class_id = result['class_id']
score = result['score']
class_name = result['class_name']
color = tuple(self.colors[class_id % 80].tolist())
# 枠を描画
draw.rectangle(bbox, outline=color, width=3)
# ラベル背景
label = f"{class_name} {score:.2f}"
try:
font = ImageFont.truetype("arial.ttf", 16)
except:
font = ImageFont.load_default()
# 文字サイズを計算
bbox_label = draw.textbbox((0, 0), label, font=font)
text_w = bbox_label[2] - bbox_label[0]
text_h = bbox_label[3] - bbox_label[1]
# ラベル背景を描画
label_bg = [bbox[0], bbox[1]-text_h-5, bbox[0]+text_w+5, bbox[1]]
draw.rectangle(label_bg, fill=color)
# 文字を描画
draw.text((bbox[0]+2, bbox[1]-text_h-3), label, fill=(255,255,255), font=font)
return np.array(image)
# シミュレーション画像を作成(デモ用)
def create_test_image() -> np.ndarray:
"""テスト画像を作成"""
h, w = 480, 640
image = np.zeros((h, w, 3), dtype=np.uint8)
# グラデーション背景
image[:, :, 0] = np.linspace(100, 200, w)[np.newaxis, :]
image[:, :, 1] = np.linspace(150, 100, h)[:, np.newaxis]
image[:, :, 2] = 180
return image
# YOLO検出フローをデモ
print("=" * 60)
print("サンプル YOLOv11 物体検出デモ")
print("=" * 60)
# 初期化
detector = SimpleYOLO().load_model()
# テスト画像を作成
test_image = create_test_image()
print(f"\n入力画像サイズ: {test_image.shape}")
# 検出をシミュレーション
results = detector.predict_dummy(test_image)
print(f"\n{len(results)} 個のオブジェクトを検出:")
for i, r in enumerate(results, 1):
print(f" {i}. {r['class_name']} (信頼度: {r['score']:.2f})")
# 可視化
visualized = detector.visualize(test_image, results)
print(f"\n可視化完了、出力画像サイズ: {visualized.shape})
# ============================================
# YOLOv11を実際に使用するコード(ultralyticsのインストールが必要)
# ============================================
print("\n" + "=" * 60)
print("YOLOv11を実際に使用するコード例:")
print("=" * 60)
print("""
# インストール:pip install ultralytics
from ultralytics import YOLO
# 1. モデルをロード
model = YOLO('yolo11n.pt') # 'yolo11s.pt', 'yolo11m.pt' なども使用可能
# 2. 予測
results = model('test_image.jpg') # 画像パス、ビデオ、0(カメラ)のいずれでも可
# 3. 結果を処理
for result in results:
# 検出ボックス
boxes = result.boxes
# セグメンテーションマスク(セグメンテーションモデルの場合)
masks = result.masks
# 結果を表示
result.show()
# 結果を保存
result.save('result.jpg')
# 4. トレーニング(オプション)
# model.train(data='coco128.yaml', epochs=100, imgsz=640)
""")
画像セグメンテーション
物体検出は矩形枠で物体を囲みますが、画像セグメンテーションはピクセルレベルで正確に、各ピクセルがどの物体に属するかを示します。
セマンティックセグメンテーション vs インスタンスセグメンテーション
画像セグメンテーションには2つの大きな分野があります:セマンティックセグメンテーションとインスタンスセグメンテーションです。
| タスク | 目的 | 例 | 代表的なモデル |
|---|---|---|---|
| セマンティックセグメンテーション | 各ピクセルを分類する(インスタンスを区別しない) | すべての人を赤、すべての車を青でマーク | FCN、U-Net、DeepLab |
| インスタンスセグメンテーション | 各ピクセルを分類し、異なるインスタンスを区別する | 人1を赤、人2をオレンジでマーク | Mask R-CNN、YOLOv8-Seg |
| パノプティックセグメンテーション | セマンティック+インスタンス、統一表現 | 「モノ」と「背景」を同時にアノテーション | Panoptic FPN、MaskFormer |
典型的な例:2人の人物と2匹の犬がいるとします。
セマンティックセグメンテーションは「人」と「犬」がここにあると言います(カテゴリのみ分類し、数は数えません)。
インスタンスセグメンテーションは「人1」、「人2」、「犬1」、「犬2」がここにあると言います(個々のインスタンスは区別されます)。
Segment Anything Model(SAM)
2023年にMeta AIはSAM(Segment Anything Model)を発表し、セグメンテーションをプロンプト駆動のインタラクティブタスクに変えました。
SAMの入力は:点、ボックス、テキスト、または粗いマスクです。
SAMの出力は:対応するオブジェクトの正確なセグメンテーションマスクです。
SAMの設計理念は次の通りです:プロンプト可能、汎化可能、ゼロショット。
実例
# SAMセグメンテーション概念デモ
# 点やボックスなどのプロンプトでセグメンテーションを行う方法を紹介
# ============================================
class SimpleSAM:
"""簡易版 SAM 概念デモ"""
def __init__(self):
self.image_embedding = None
print("SAM概念デモ初期化")
def set_image(self, image: np.ndarray):
"""画像をエンコード(一度だけ実行)"""
print("画像をembeddingにエンコード中...")
self.image_embedding = "image_encoded"
return self
def predict_from_point(self, point: tuple, point_label: int = 1):
"""
1つの点からセグメンテーションを実行
パラメータ:
point: (x, y) 座標
point_label: 1は前景、0は背景
"""
print(f"点 {point} からセグメンテーション({'前景' if point_label == 1 else '背景'})")
return "mask_from_point"
def predict_from_box(self, box: tuple):
"""境界ボックスからセグメンテーションを実行"""
x1, y1, x2, y2 = box
print(f"ボックス [{x1}, {y1}, {x2}, {y2}] からセグメンテーション")
return "mask_from_box"
def predict_from_points(self, points: list, labels: list):
"""複数の点からセグメンテーションを実行"""
print(f"{len(points)} 個の点からセグメンテーション")
return "mask_from_points"
# SAMの使用フローをデモ
print("=" * 60)
print("サンプル SAMセグメンテーション概念デモ")
print("=" * 60)
sam = SimpleSAM()
# 1. 画像をセットアップ(一度エンコード)
test_img = create_test_image()
sam.set_image(test_img)
# 2. 異なるプロンプトでセグメンテーション
print()
mask1 = sam.predict_from_point((100, 200), point_label=1)
print()
mask2 = sam.predict_from_box((50, 50, 200, 300))
print()
mask3 = sam.predict_from_points([(100, 100), (150, 150)], [1, 1])
# ============================================
# SAMを実際に使用するコード例
# ============================================
print("\n" + "=" * 60)
print("SAMを実際に使用するコード例:")
print("=" * 60)
print("""
# インストール:pip install segment-anything torch torchvision opencv-python
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
# 1. モデルをロード
# checkpointをダウンロード: https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")
predictor = SamPredictor(sam)
# 2. 画像をセットアップ
image = cv2.imread("test_image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image)
# 3. 点プロンプトでセグメンテーション
input_point = np.array([[300, 250]]) # プロンプト点の座標
input_label = np.array(
masks, scores, logits = predictor.predict(
point_coords=input_point,
point_labels=input_label,
multimask_output=True
)
# 4. 結果を可視化
for i, mask in enumerate(masks):
color = np.array([30, 144, 255])
h, w = mask.shape
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
cv2.imwrite(f"mask_{i}.jpg", mask_image)
""")
産業におけるセグメンテーションの応用
画像セグメンテーションは多くの産業アプリケーションの中核技術です:
| 分野 | 応用シーン | タスクタイプ |
|---|---|---|
| 医用画像 | 腫瘍セグメンテーション、臓器測定 | セマンティックセグメンテーション |
| 自動運転 | 走行可能領域、車線認識 | セマンティックセグメンテーション |
| リモートセンシング画像 | 土地被覆分類、建物抽出 | セマンティックセグメンテーション |
| スマート製造 | 欠陥検出、部品測定 | インスタンスセグメンテーション |
| ビデオ編集 | 人物切り抜き、背景置換 | インスタンスセグメンテーション |
拡散モデル(Diffusion Models)
拡散モデルはAI画像生成の中核技術であり、Stable Diffusion、DALL-E 3、Midjourneyはすべてこれに基づいています。
順方向拡散プロセス(ノイズ付加)
前方拡散は単純なプロセスです:画像にガウスノイズを段階的に追加し、完全なノイズになるまで続けます。
これは決定的なプロセスであり、各ステップで少しだけノイズを追加します。数学的公式を使用して、任意の時点のノイズ量を正確に計算できます。
実例
# 拡散モデルの前方プロセス(ノイズ付加)をデモ
# ============================================
import numpy as np
import matplotlib.pyplot as plt
class ForwardDiffusion:
"""前方拡散プロセスのデモ"""
def __init__(self, num_timesteps: int = 1000):
self.num_timesteps = num_timesteps
# betaスケジュールを定義(beta_startからbeta_endまで線形増加)
self.beta_start = 0.0001
self.beta_end = 0.02
self.betas = np.linspace(self.beta_start, self.beta_end, num_timesteps)
# alphaとalpha_barを計算
self.alphas = 1.0 - self.betas
self.alphas_bar = np.cumprod(self.alphas)
def q_sample(self, x0: np.ndarray, t: int) -> tuple:
"""
x0からt時点のxtを直接計算
パラメータ:
x0: 元画像 (H, W, 3)
t: タイムステップ(0 <= t < num_timesteps)
戻り値:
xt: t時点の画像
noise: 追加されたノイズ
"""
sqrt_alpha_bar_t = np.sqrt(self.alphas_bar[t])
sqrt_one_minus_alpha_bar_t = np.sqrt(1 - self.alphas_bar[t])
# 同じ形状のランダムノイズを生成
noise = np.random.randn(*x0.shape)
# xtを一気に計算
xt = sqrt_alpha_bar_t * x0 + sqrt_one_minus_alpha_bar_t * noise
return xt, noise
# シンプルなテスト画像を作成:中央に明るい円
def create_diffusion_test_image():
h, w = 64, 64
x = np.linspace(-1, 1, w)
y = np.linspace(-1, 1, h)
xx, yy = np.meshgrid(x, y)
r = np.sqrt(xx**2 + yy**2)
image = np.exp(-r**2 / 0.1) # ガウス分布の明るい円
image = (image - image.min()) / (image.max() - image.min()) # [0, 1] に正規化
image = np.stack([image, image*0.8, image*0.5], axis=-1) # 3チャンネルに変換
return image
print("=" * 60)
print("サンプル 前方拡散プロセスのデモ")
print("=" * 60)
# 拡散プロセスを初期化
diffusion = ForwardDiffusion(num_timesteps=1000)
# テスト画像を作成
x0 = create_diffusion_test_image()
print(f"元画像の形状: {x0.shape}")
# 異なるタイムステップのノイズ付加結果を表示
timesteps_to_show = [0, 100, 200, 300, 500, 1000]
print("\n異なるタイムステップのノイズ付加レベル:")
for t in timesteps_to_show:
if t < 1000:
xt, noise = diffusion.q_sample(x0, t)
alpha_bar = diffusion.alphas_bar[t]
print(f" t={t:4d}: alpha_bar={alpha_bar:.4f}, SN比={alpha_bar/(1-alpha_bar):.4f}")
else:
print(f" t={t:4d}: 純粋なノイズ")
print("\n前方拡散の核心的な公式:")
print(" q(x_t | x_0) = N(x_t; sqrt(alpha_bar_t) * x0, (1 - alpha_bar_t) * I)")
print("\nこの公式を使えば、x0 から任意の時刻 t の x_t を一度に計算でき、ステップごとの反復は不要です!)
逆方向ノイズ除去プロセス
逆過程は前向き過程の逆です:純粋なノイズから始めて、段階的にノイズを予測して除去し、最終的に画像を得ます。。
これはモデルに学習させる内容です:xt と t が与えられたとき、加えられたノイズが何かを予測します。
学習目標:モデルが予測したノイズと実際のノイズの平均二乗誤差を最小化すること。
U-Net アーキテクチャ
拡散モデルの中心はU-Netネットワークで、その形状はアルファベットの「U」に似ています:左側でダウンサンプリングして圧縮し、右側でアップサンプリングして復元します。
U-Netの鍵はスキップ接続(Skip Connection)で、ダウンサンプリング時の特徴をアップサンプリング時の対応する層に直接渡し、詳細な情報を保持します。
DDPM vs DDIM サンプリング
モデルを訓練した後、ノイズからサンプリングして画像を生成します。サンプラーによって速度と品質が異なります。
| サンプラー | 正式名称 | ステップ数 | 特徴 |
|---|---|---|---|
| DDPM | Denoising Diffusion Probabilistic Models | 1000 | 元の方法、品質は良いが遅い |
| DDIM | Denoising Diffusion Implicit Models | 50-100 | 決定論的サンプリング、高速 |
| LMS | Linear Multistep Method | 30-50 | 高速で品質も良い |
| DPM-Solver | DPM-Solver | 10-20 | 超高速、数ステップで良い結果が出せる |
現在のStable DiffusionはデフォルトでDPM-Solver++を使用しており、通常20〜30ステップで高品質な結果が得られ、初期のDDPMより数十倍高速です。
Stable Diffusion アーキテクチャ
Stable Diffusionはピクセル空間で直接動作するのではなく、潜在空間(Latent Space)で動作するため、より高速で効率的です。
完全なStable Diffusionは3つの部分で構成されています:
1. VAE(Variational Autoencoder):画像を潜在ベクトルに圧縮したり、潜在ベクトルを画像に復元したりします。
2. UNet:中心となるデノイジングネットワークで、潜在ベクトルとタイムステップ、プロンプトの埋め込みを受け取り、ノイズを予測します。
3. Text Encoder(CLIP):テキストプロンプトを埋め込みに変換し、モデルに何を生成するかを伝えます。
実例
# Stable Diffusion 概念デモ
# 完全な生成プロセスを示す
# ============================================
class SimpleStableDiffusion:
"""簡易版 Stable Diffusion 概念デモ"""
def __init__(self):
print("Stable Diffusion 概念デモ初期化")
def encode_text(self, prompt: str):
"""テキストプロンプトをエンコード"""
print(f"プロンプトをエンコード: '{prompt}'")
return "text_embedding"
def encode_image(self, image: np.ndarray):
"""VAEで画像を潜在空間にエンコード"""
print("画像を潜在空間にエンコード(VAEエンコーダー)")
return "latent_code"
def decode_latent(self, latent: str):
"""VAEで潜在空間から画像をデコード"""
print(潜に空間から画像をデコード(VAEデコーダー))
return "decoded_image"
def denoise_step(self, latent: str, text_embedding: str, t: int):
"""1ステップのデノイジング"""
print(f" デノイジングステップ t={t}")
return "denoised_latent"
def generate(self, prompt: str, num_inference_steps: int = 50):
"""完全な生成プロセス"""
print("=" * 60)
print(f"生成開始: '{prompt}'")
print("=" * 60)
# 1. テキストをエンコード
text_emb = self.encode_text(prompt)
# 2. ランダムノイズから開始
print("\nランダムノイズを初期化...")
latent = "random_noise"
# 3. 段階的にデノイズ
print(f"\n開始デノイジングループ({num_inference_steps} ステップ):")
for t in reversed(range(num_inference_steps)):
latent = self.denoise_step(latent, text_emb, t)
# 4. デコードして画像を取得
print("\n潜にベクトルを画像にデコード...)
image = self.decode_latent(latent)
print("\n生成完了!")
return image
# 生成プロセスのデモ
sd = SimpleStableDiffusion()
image = sd.generate(
prompt="庭にいるかわいいオレンジ色の猫",
num_inference_steps=20
)
# ============================================
# 実際にStable Diffusionを使用するコード例
# ============================================
print("\n" + "=" * 60)
print("実際にStable Diffusionを使用するコード例:")
print("=" * 60)
print("""
# インストール:pip install diffusers transformers accelerate torch
from diffusers import StableDiffusionPipeline
import torch
# 1. モデルをロード
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16
)
pipe = pipe.to("cuda")
# 2. テキストから画像生成
prompt = "a cute orange cat in a garden"
image = pipe(prompt).images[0]
# 3. 結果を保存
image.save("cat_garden.png")
# 4. 画像から画像生成
from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image
img_pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16
).to("cuda")
init_image = Image.open("input.jpg").convert("RGB")
init_image = init_image.resize((512, 512))
image = img_pipe(
prompt="make it look like a painting",
image=init_image,
strength=0.75 # 変化の程度
).images[0]
image.save("painted.png")
# 5. Inpainting(部分修正)
from diffusers import StableDiffusionInpaintPipeline
inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16
).to("cuda")
image = inpaint_pipe(
prompt="put a hat on the cat",
image=init_image,
mask_image=mask_image # マスク画像、白い領域が修正対象の部分
).images[0]
""")
CLIP:マルチモーダルアライメントの基礎
CLIP(Contrastive Language-Image Pre-training)はOpenAIが2021年に発表した研究で、テキストと画像を初めて同じベクトル空間に真に整列させました。
対比学習の原理
CLIPの訓練方法は対比学習です:正しい画像・テキストペアの類似度を高くし、誤ったペアの類似度を低くします。。
訓練時、1つのバッチにN枚の画像とN個のテキスト(1対1対応)があり、N×N個の可能な画像・テキストペアを形成します。
対角線は一致する正例サンプルで、他はすべて不一致の負例サンプルです。
学習目標は:正例サンプルの類似度をできるだけ大きく、負例サンプルの類似度をできるだけ小さくすることです。
画像とテキストのアライメント学習
CLIPは2つのエンコーダーで構成されます:
1. Image Encoder:画像をベクトルにエンコード(ResNetやViTを使用可能)。
-
2. Text Encoder:テキストをベクトルにエンコード(Transformer)。
2つのベクトルを同じ空間に投影した後、コサイン類似度で画像とテキストの一致度を計算します。
実例
# CLIP 概念デモ:対比学習と画像・テキストアライメント
# ============================================
import torch
import torch.nn.functional as F
class SimpleCLIP:
"""簡易版 CLIP 概念デモ"""
def __init__(self, embed_dim: int = 512):
self.embed_dim = embed_dim
# 簡単なシミュレーション:実際のエンコードではなく、ランダム射影のみ
print("CLIP 概念デモ初期化")
print(f"Embedding 次元: {embed_dim}")
def encode_image(self, image: str) -> torch.Tensor:
"""画像エンコードのシミュレーション"""
# 実際にはここは Vision Transformer または ResNet
return torch.randn(1, self.embed_dim)
def encode_text(self, text: str) -> torch.Tensor:
"""テキストエンコードのシミュレーション"""
# 実際にはここは Text Transformer
return torch.randn(1, self.embed_dim)
def compute_similarity(self, image_emb: torch.Tensor, text_emb: torch.Tensor) -> float:
"""コサイン類似度の計算"""
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
return (image_emb @ text_emb.T).item()
# CLIP推論プロセスのデモ
print("=" * 60)
print("サンプル CLIP ゼロショット分類デモ")
print("=" * 60)
clip = SimpleCLIP(embed_dim=512)
# 1枚の画像があると仮定
print("\n1. 画像をエンコード...")
image_emb = clip.encode_image("猫の写真")
# いくつかの候補クラスがあると仮定
candidates = ["犬の写真", "猫の写真", "車", "人"]
print(f"\n2. 候補テキストをエンコード: {candidates}")
# 類似度を計算
print("\n3. 画像とテキストの類似度を計算:")
for text in candidates:
text_emb = clip.encode_text(text)
sim = clip.compute_similarity(image_emb, text_emb)
print(f" '{text}' → 類似度: {sim:.3f}")
print("\n(実際には、「猫の写真」が最も高い類似度になります)")
# ============================================
# 実際にCLIPを使用するコード例
# ============================================
print("\n" + "=" * 60)
print("実際にCLIPを使用するコード例:")
print("=" * 60)
print("""
# インストール:pip install clip torch torchvision
import clip
import torch
from PIL import Image
# 1. モデルをロード
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# 2. 画像を準備
image = preprocess(Image.open("cat.jpg")).unsqueeze(0).to(device)
# 3. テキストを準備
text = clip.tokenize([
"a photo of a dog",
"a photo of a cat",
"a photo of a car",
"a photo of a person"
]).to(device)
# 4. 推論
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
logits_per_image, logits_per_text = model(image, text)
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
# 5. 結果を出力
print("予測確率:")
for i, p in enumerate(probs[0]):
print(f" {i+1}. {p:.2%}")
""")
Zero-Shot 分類能力
CLIPの最もエキサイティングな能力はZero-Shot分類です:ターゲットデータセットで訓練する必要がなく、直接分類できます。
従来のImageNetで訓練されたモデルは、ImageNetの1000クラスしか分類できず、新しいクラスを追加するには再訓練が必要です。
CLIPは任意のテキストでクラスを記述できます。例:「猫の写真」、「芝生に座っているオレンジ色の猫」、「猫のスケッチ画」。
CLIPの意義はゼロショット分類だけでなく、一般的な「視覚-言語」インターフェースを確立したことにあり、その後の多くのモデル(Stable Diffusion、視覚言語モデルなど)がその上に構築されています。
視覚言語モデル(VLM)
視覚言語モデル(Vision-Language Model、VLM)は、画像理解と言語生成を組み合わせ、モデルが「画像を見て話す」ことを可能にします。
LLaVA アーキテクチャ
LLaVA(Large Language and Vision Assistant)はオープンソースのVLMで、その設計は簡潔で明確であり、入門学習に適しています。
LLaVAのアーキテクチャは3つの部分に分かれます:
-
1. Vision Encoder:CLIPの視覚エンコーダーで、画像を埋め込みに変換します。
-
2. Projection Layer:視覚 embedding を LLM 入力と同じ次元に投影する。
-
3. LLM:大規模言語モデル(Vicuna、LLaMA など)で、連結された画像とテキストの入力を受け取り、回答を生成する。
トレーニングは2つのステップに分かれます:
-
1. 事前学習段階:Projection Layer のみを学習し、大量の画像とテキストのペアを使って整列させる。
-
2. 指示チューニング段階:視覚指示データセット(LLaVA-Instruct など)を使用してモデル全体を学習する。
視覚エンコーダとLLMの接続
視覚と言語を接続する鍵は次の点です:画像を言語モデルが理解できる token シーケンスとして表現すること。
いくつかの一般的な接続方法があります:
| 方式 | 特徴 | 代表モデル |
|---|---|---|
| 特殊 token | 1つの [IMG] token で画像全体を表す | 初期モデル |
| シーケンス連結 | 画像の patch embedding をテキストの前に直接連結する | LLaVA、GPT-4V |
| 交差注意 | LLM に視覚特徴への交差注意を追加する | BLIP-2、Flamingo |
実例
# 視覚言語モデル(VLM)概念デモ
# 視覚と言語の入力を連結する方法を示す
# ============================================
class SimpleVLM:
"""簡易版視覚言語モデル"""
def __init__(self, vocab_size: int = 50000, hidden_size: int = 768):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
print("""簡易版 VLM 初期化""")
def encode_vision(self, image: str) -> torch.Tensor:
"""画像をシーケンスにエンコードする"""
# 256 個の視覚 token があると仮定
return torch.randn(1, 256, self.hidden_size)
def encode_text(self, text: str) -> torch.Tensor:
"""テキストをシーケンスにエンコードする"""
# テキストには 16 個の token があると仮定
return torch.randn(1, 16, self.hidden_size)
def generate(self, image: str, question: str) -> str:
"""画像とテキストを連結して回答を生成する"""
print("=" * 60)
print(f"質問: {question}")
print("=" * 60)
# 1. 画像とテキストをエンコード
print("\n1. 画像をエンコード中...)
vision_emb = self.encode_vision(image)
print("2. テキストをエンコード中...")
text_emb = self.encode_text(question)
# 3. 連結:[視覚シーケンス] + [テキストシーケンス]
print("\n3. 視覚シーケンスとテキストシーケンスを連結中...)
print(f" 視覚 embedding 形状: {vision_emb.shape}")
print(f" テキスト embedding 形状: {text_emb.shape}")
combined = torch.cat([vision_emb, text_emb], dim=1)
print(f" 連結後の形状: {combined.shape}")
# 4. LLM が回答を生成
print("\n4. LLM が回答を生成中...)
return "これはかわいい茶トラの猫です。とても嬉しそうです。"
# VLM の Q&A をデモ
vlm = SimpleVLM()
answer = vlm.generate(
image="茶トラの猫の写真",
question="この画像には何が写っていますか?説明してください。"
)
print(f"\n回答: {answer}")
# ============================================
# LLaVA を実際に使用するコード例
# ============================================
print("\n" + "=" * 60)
print("LLaVA を実際に使用するコード例:")
print("=" * 60)
print("""
# LLaVA は多くの VRAM を必要とするため、transformers または llava ライブラリの使用を推奨
from transformers import AutoProcessor, AutoModelForVisionAndLanguageGeneration
import torch
from PIL import Image
# 1. モデルとプロセッサをロード
model_id = "llava-hf/llava-1.5-7b-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForVisionAndLanguageGeneration.from_pretrained(
model_id,
torch_dtype=torch.float16,
device_map="auto"
)
# 2. 入力を準備
image = Image.open("cat.jpg")
prompt = "USER: <image>\\nこの画像には何が写っていますか?説明してください。 ASSISTANT:
inputs = processor(images=image, text=prompt, return_tensors="pt").to("cuda")
# 3. 生成
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=500)
answer = processor.decode(output[0], skip_special_tokens=True)
print(answer)
""")
実践:画像分類 + 物体検出の完全プロジェクト
では、これまで学んだ知識を統合して、完全な実践プロジェクトを作りましょう。
実例
# 実践プロジェクト:完全なビジョン AI パイプライン
# 画像分類、物体検出、結果の可視化を含む
# ============================================
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
from PIL import Image
import json
from pathlib import Path
class VisionPipeline:
"""
完全なビジョン AI パイプライン
機能:
1. 画像分類
2. 物体検出
3. 結果の集約と可視化
"""
def __init__(self, device: str = "cpu"):
self.device = device
self.classifier = None
self.detector = None
print(f"サンプル Vision Pipeline 初期化(デバイス: {device})")
def build_classifier(self, num_classes: int = 10):
"""画像分類器を構築"""
print("\n画像分類器を構築中...)
# 前述の SimpleCNN を使用
self.classifier = SimpleCNN(num_classes=num_classes).to(self.device)
print("分類器の構築が完了しました!")
return self
def build_detector(self):
"""物体検出器を構築"""
print("\n物体検出器を構築中...)
self.detector = SimpleYOLO()
print("検出器の構築が完了しました!")
return self
def load_pretrained_weights(self, classifier_path: str = None):
"""事前学習済みの重みをロード"""
if classifier_path and self.classifier:
print(f"\n分類器の重みをロード中: {classifier_path}")
# 実際には: self.classifier.load_state_dict(torch.load(classifier_path))
return self
def classify_image(self, image: np.ndarray) -> tuple:
"""
画像分類
戻り値:
(pred_class_id, pred_class_name, confidence)
"""
if self.classifier is None:
raise ValueError("まず分類器を構築してください: build_classifier()")
# 前処理
if isinstance(image, np.ndarray):
if image.ndim == 2: # グレースケール画像
image = np.stack([image]*3, axis=-1)
image = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0
image = F.interpolate(image.unsqueeze(0), size=(32, 32), mode='bilinear')
image = image.to(self.device)
# 推論
self.classifier.eval()
with torch.no_grad():
logits = self.classifier(image)
probs = F.softmax(logits, dim=-1)
confidence, pred_idx = probs.max(dim=-1)
# 結果を返す
class_names = [
'airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck'
]
pred_class = class_names[pred_idx.item()]
return pred_idx.item(), pred_class, confidence.item()
def detect_objects(self, image: np.ndarray) -> list:
"""物体検出"""
if self.detector is None:
raise ValueError("まず検出器を構築してください: build_detector()")
# シミュレーション検出を使用
return self.detector.predict_dummy(image)
def process_image(self, image: np.ndarray) -> dict:
"""
1枚の画像を完全に処理する
戻り値:
すべての結果を含む辞書
"""
print("\n" + "=" * 60)
print("画像の処理を開始")
print("=" * 60)
results = {}
# 1. 画像分類
if self.classifier is not None:
print("\n[1/3] 画像分類を実行中...)
class_id, class_name, conf = self.classify_image(image)
results['classification'] = {
'class_id': class_id,
'class_name': class_name,
'confidence': conf
}
print(f" → 分類結果: {class_name}(信頼度: {conf:.2%})")
# 2. 物体検出
if self.detector is not None:
print("\n[2/3] 物体検出を実行中...)
detections = self.detect_objects(image)
results['detections'] = detections
print(f" → {len(detections)} 個の物体を検出:")
for det in detections:
print(f" - {det['class_name']} ({det['score']:.2f})")
# 3. 可視化
print("\n[3/3] 可視化を生成中...)
if self.detector is not None:
vis_image = self.detector.visualize(image, detections)
results['visualization'] = vis_image
print(" → 可視化が完了")
print("\n" + "=" * 60)
print(画像処理が完了しました!)
print("=" * 60)
return results
def save_results(self, results: dict, output_dir: str = "output"):
"""結果をファイルに保存"""
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
# JSON 結果を保存
json_result = {
'classification': results.get('classification'),
'detections': [
{k: v for k, v in det.items() if k != 'bbox'}
for det in results.get('detections', [])
]
}
with open(output_path / "results.json", "w") as f:
json.dump(json_result, f, indent=2, ensure_ascii=False)
# 可視化画像を保存
if 'visualization' in results:
vis = Image.fromarray(results['visualization'])
vis.save(output_path / "visualization.jpg")
print(f"\n結果は {output_path}/ に保存されました")
# 完全な学習例
class SimpleDataset(Dataset):
"""シンプルなシミュレーションデータセット"""
def __init__(self, num_samples: int = 100):
self.num_samples = num_samples
# ダミーデータを生成
self.images = torch.randn(num_samples, 3, 32, 32)
self.labels = torch.randint(0, 10, (num_samples,))
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
return self.images[idx], self.labels[idx]
def train_classifier(pipeline: VisionPipeline, num_epochs: int = 5):
"""分類器を学習する完全なフロー"""
print("\n" + "=" * 60)
print("分類器の学習を開始")
print("=" * 60)
# 1. データを準備
print("\nデータセットを準備中...)
train_dataset = SimpleDataset(1000)
val_dataset = SimpleDataset(200)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32)
print(f"訓練セット: {len(train_dataset)} サンプル")
print(f"検証セット: {len(val_dataset)} サンプル")
# 2. オプティマイザと損失関数
optimizer = torch.optim.Adam(pipeline.classifier.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
# 3. 学習ループ
print("\n学習を開始中...)
for epoch in range(num_epochs):
pipeline.classifier.train()
total_loss = 0.0
correct = 0
total = 0
for images, labels in train_loader:
images, labels = images.to(pipeline.device), labels.to(pipeline.device)
optimizer.zero_grad()
outputs = pipeline.classifier(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
train_acc = correct / total
avg_loss = total_loss / len(train_loader)
# 検証
pipeline.classifier.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in val_loader:
images, labels = images.to(pipeline.device), labels.to(pipeline.device)
outputs = pipeline.classifier(images)
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
val_acc = correct / total
print(f"Epoch {epoch+1}/{num_epochs} - "
f"損失: {avg_loss:.4f}, "
f"訓練精度: {train_acc:.2%}, "
f"検証精度: {val_acc:.2%}")
print("\n学習が完了しました!)
# ============================================
# 完全な実践プロジェクトを実行
# ============================================
print("=" * 60)
print("サンプル ビジョン AI 完全実践プロジェクト")
print("=" * 60)
# 1. パイプラインを作成
pipeline = VisionPipeline(device="cuda" if torch.cuda.is_available() else "cpu")
# 2. モデルを構築
pipeline.build_classifier(num_classes=10)
pipeline.build_detector()
# 3. 分類器を学習
train_classifier(pipeline, num_epochs=3)
# 4. 画像を処理
test_image = create_test_image()
results = pipeline.process_image(test_image)
# 5. 結果を保存
pipeline.save_results(results, output_dir="サンプル_output")
print("\n" + "=" * 60)
print("プロジェクトの実行が完了しました!")
print("=" * 60)
print("\n次の学習ステップの提案:)
print(" 1. 実際のデータセット(CIFAR-10 など)で学習を試す")
print(" 2. 事前学習済みモデルを使用してファインチューニングする")
print(" 3. より複雑なモデルアーキテクチャを試す")
print(" 4. 実際のアプリケーションにデプロイする")