python
import torch
import torch.nn as nn
from torchvision.models import alexnet, AlexNet_Weights
from torchvision.ops import roi_align, batched_nms, box_iou
'''
R-CNN の検出の手順(論文 2.1〜2.2 節)と枠の回帰(付録 C の式(1)〜(9))を、PyTorch で小さく書いた例。
候補の領域(Selective Search)は PyTorch にないので、OpenCV の ximgproc などで作ったものを受け取る。
'''
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
num_classes = 20 # PASCAL VOC の物体のクラス数 N(背景は含まない)
input_size, context = 227, 16 # CNN の入力の大きさと、周りに含める文脈の画素数 p
def warp_regions(image, boxes):
"""候補の領域を、周りに p 画素の文脈を足して 227×227 に引き伸ばす(縦横の比は保たない)。
image:平均を引いた画像 [3, H, W]。boxes:[R, 4](x1, y1, x2, y2)"""
scale = input_size / (input_size - 2 * context) # 引き伸ばした後に 16 画素の余白が入るよう枠を広げる
cx, cy = (boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2
w, h = (boxes[:, 2] - boxes[:, 0]) * scale, (boxes[:, 3] - boxes[:, 1]) * scale
grown = torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], dim=1)
# 画像の外は 0(平均を引いた後なので、論文の「画像の平均で埋める」と同じ)
rois = torch.cat([torch.zeros(len(grown), 1, device=grown.device), grown], dim=1)
return roi_align(image[None], rois, output_size=(input_size, input_size), sampling_ratio=1, aligned=True)
class RCNNFeatures(nn.Module):
"""AlexNet で、pool5(枠の回帰用)と fc7(SVM 用、4096 次元)の特徴を取り出す"""
def __init__(self):
super().__init__()
net = alexnet(weights=AlexNet_Weights.IMAGENET1K_V1) # ImageNet で事前学習した重み
self.conv = net.features # 畳み込み 5 層(最後に最大値プーリング)
self.pool = net.avgpool # 6×6 にそろえる
self.fc = net.classifier[:-1] # fc6・fc7(最後の 1000 クラスの層を外す)
def forward(self, x):
pool5 = torch.flatten(self.pool(self.conv(x)), 1) # [R, 9216]
return pool5, self.fc(pool5) # fc7:[R, 4096]
def encode(proposals, gt):
"""学習の目標 t(式(6)〜(9))。枠は (x1, y1, x2, y2)"""
pw, ph = proposals[:, 2] - proposals[:, 0], proposals[:, 3] - proposals[:, 1]
px, py = proposals[:, 0] + pw / 2, proposals[:, 1] + ph / 2
gw, gh = gt[:, 2] - gt[:, 0], gt[:, 3] - gt[:, 1]
gx, gy = gt[:, 0] + gw / 2, gt[:, 1] + gh / 2
return torch.stack([(gx - px) / pw, (gy - py) / ph, torch.log(gw / pw), torch.log(gh / ph)], dim=1)
def decode(proposals, d):
"""補正した枠(式(1)〜(4))。d:[R, 4](d_x, d_y, d_w, d_h)"""
pw, ph = proposals[:, 2] - proposals[:, 0], proposals[:, 3] - proposals[:, 1]
px, py = proposals[:, 0] + pw / 2, proposals[:, 1] + ph / 2
gx, gy = pw * d[:, 0] + px, ph * d[:, 1] + py
gw, gh = pw * torch.exp(d[:, 2]), ph * torch.exp(d[:, 3])
return torch.stack([gx - gw / 2, gy - gh / 2, gx + gw / 2, gy + gh / 2], dim=1)
def fit_box_regressor(pool5, proposals, gt_boxes, lam=1000.0, iou_thresh=0.6):
"""1 クラスぶんの枠の回帰を、リッジ回帰(式(5))の閉じた形で解く。IoU > 0.6 の候補だけを使う"""
iou, idx = box_iou(proposals, gt_boxes).max(dim=1)
keep = iou > iou_thresh
X, T = pool5[keep], encode(proposals[keep], gt_boxes[idx[keep]])
A = X.T @ X + lam * torch.eye(X.shape[1], device=X.device)
return torch.linalg.solve(A, X.T @ T) # W:[9216, 4]
@torch.no_grad()
def detect(image, proposals, features, svm, box_weights, nms_thresh=0.3, score_thresh=0.0):
"""テストの手順。svm:nn.Linear(4096, N)(クラスごとの線形 SVM を並べたもの)
box_weights:[N, 9216, 4](クラスごとの枠の回帰の重み)。nms_thresh は論文では検証データで選ぶ値"""
features.eval() # ドロップアウトを止める(学習中は model.train())
pool5, fc7 = features(warp_regions(image, proposals))
scores = svm(fc7) # [R, N]:2000×4096 と 4096×N の行列の積
boxes, labels, keep_scores = [], [], []
for c in range(scores.shape[1]):
s = scores[:, c]
m = s > score_thresh
if m.any():
d = pool5[m] @ box_weights[c] # d_*(P) = w_*^T φ5(P)
boxes.append(decode(proposals[m], d))
labels.append(torch.full((int(m.sum()),), c, device=s.device))
keep_scores.append(s[m])
if not boxes:
return torch.zeros(0, 4), torch.zeros(0), torch.zeros(0, dtype=torch.long)
boxes, keep_scores, labels = torch.cat(boxes), torch.cat(keep_scores), torch.cat(labels)
keep = batched_nms(boxes, keep_scores, labels, nms_thresh) # クラスごとの非最大値抑制
return boxes[keep], keep_scores[keep], labels[keep]
# 使い方(image は平均を引いた [3, H, W]、proposals は Selective Search の [約 2000, 4])
features = RCNNFeatures().to(device)
svm = nn.Linear(4096, num_classes).to(device) # 学習済みの SVM の重みを読み込んで使う
box_weights = torch.zeros(num_classes, 9216, 4, device=device)
image = torch.randn(3, 375, 500, device=device)
proposals = torch.tensor([[50., 60., 200., 300.], [120., 40., 400., 330.]], device=device)
boxes, scores, labels = detect(image, proposals, features, svm, box_weights)
print(boxes.shape, scores.shape, labels.shape)