目录

Faster-R-CNN原理详解以及Pytorch实现模型训练与推理

Faster R-CNN原理详解以及Pytorch实现模型训练与推理

《——往期经典推荐——》

一、

项目名称项目名称
1.【 】2.【 】
3.【 】4.【 】
5.【 】6.【 】
7.【 】8.【 】
9.【 】10.【 】
11.【 】12.【 】
13.【 】14.【 】
15.【 】16.【 】
17.【 】18.【 】
19.【 】20.【 】
21.【 】22.【 】
23.【 】24.【 】
25.【 】26.【 】
27.【 】28.【 】
29.【 】30.【 】
31.【 】32.【 】
33.【 】34.【 】
35.【 】36.【 】
37.【 】38.【 】
39.【 】40.【 】
41.【 】42.【 】
43.【 】44.【 】
45.【 】46.【 】
47.【 】48.【 】
49.【 】50.【 】
51.【 】52.【 】
53.【 】54.【 】
55.【 】56.【 】
57.【 】58.【 】
59.【 】60.【 】
61.【 】62.【 】
63.【 】64.【 】
65.【 】66.【 】
67.【 】68.【 】
69.【 】70.【 】
71.【 】72.【 】
73.【 】74.【 】
75.【 】76.【 】
77.【 】78.【 】
79.【 】80.【 】
81.【 】82.【 】
83.【 】84.【 】
85.【 】86.【 】
87.【 】88.【 】

二、 ,已更新31期,欢迎关注,持续更新中~~

三、

四、

持续更新中~~

,持续更新中~

《——正文——》

引言

目前大多数SOTA模型都是建立在Faster-RCNN模型的基础之上。 Faster R-CNN 是一 种对象检测 模型,它可以识别图像中的对象,并在它们周围绘制边界框,同时还可以对这些对象进行分类。这是一个两级探测器:

  1. 阶段1 :提出图像中可能包含对象的潜在区域。这是由**Region Proposal Network(RPN)**处理的。
  2. 阶段2 :使用这些建议的区域来预测对象的 类别 ,并 细化 边界框以更好地匹配对象。

Faster R-CNN架构

https://i-blog.csdnimg.cn/img_convert/2343d258f1e764306efc39ffe3694f1d.jpeg

第一阶段:区域提案网络(RPN)

骨干网

  • 图像通过卷积网络(如ResNet或VGG16)。
  • 这将从图像中提取重要特征并创建 特征图

锚框

  • 锚框 是放置在特征图上的点上的不同大小和形状的框。
  • 每个锚框表示可能的对象位置。
  • 在特征图上的每个点处,生成具有不同大小和纵横比的锚框。

目标分类

  • RPN预测每个锚框是 背景 (无对象)还是 前景 (包含对象)。
  • 正(前景)锚点 :与实际对象高度重叠的框。
  • 负(背景)锚点 :与对象几乎没有重叠的框。

边界框优化

  • RPN还通过预测 偏移 (调整)来细化锚框,以更好地将其与实际对象对齐。

损失函数

I)分类损失 :帮助模型决定锚是背景还是前景。

II)回归损失 :帮助调整锚框以更精确地适应对象。

阶段2:目标分类和框细化

Region Proposals区域建议

  • 在RPN之后,我们得到 区域建议 (可能包含对象的细化框)。

ROI池化

  • 区域建议有不同的大小,但神经网络需要固定大小的输入。
  • ROI池化 通过将所有区域方案划分为较小的区域并应用池化来将它们调整为固定大小,从而使它们均匀一致。

对象分类

  • 每个区域建议通过一个小网络来预测 类别 (例如,狗、汽车等)里面的物体。
  • 交叉熵损失 用于将对象分类到类别中。

边界框优化(再次)

  • 使用偏移量,再次细化区域建议,以更好地匹配实际对象。
  • 这使用 回归损失 来调整建议。

多任务学习

  • 第二阶段的网络同时学习预测对象类别和优化边界框。

推理(测试/预测时间):

  • Top Region Proposals :在测试过程中,模型会生成大量的区域建议,但只有 顶级建议 (具有最高分类分数)会被传递到第二阶段。
  • 最终预测 :第二阶段预测最终的类别和边界框。
  • 非最大抑制 :一种称为 非最大抑制的 技术被应用于删除重复或重叠的框,只保留最好的框。

训练

两种训练方式

  1. 分阶段训练 :首先训练区域建议网络(RPN),然后训练分类器和回归器。
  2. 同时训练 :同时训练两个阶段(更快,更有效)。

在PyTorch中实现和微调Faster R-CNN

步骤1:安装所需的库

pip install torch torchvision

步骤2:导入所需库

import torch
from torch.utils.data import DataLoader
import torchvision
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from torchvision.datasets import ImageFolder
from torchvision import transforms
import torchvision.transforms as T
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor

步骤3:加载预训练的Faster R-CNN模型

PyTorch的 torchvision 提供了一个在COCO上预训练的更快的R-CNN模型。您可以通过更改最后一层中的类数量来修改您自己的数据集。

# Load the pre-trained Faster R-CNN model with a ResNet-50 backbone
model = fasterrcnn_resnet50_fpn(pretrained=True)

# Number of classes (your dataset classes + 1 for background)
num_classes = 3  # For example, 2 classes + background

# Get the number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features

# Replace the head of the model with a new one (for the number of classes in your dataset)
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)

步骤4:准备数据集

  • Faster R-CNN需要图像和相应的注释(边界框和标签)。
  • **您的数据集应返回: 包括边界框( *框* )和标签( *标签* )的图像和目标字典。

如有必要,请创建自定义数据集类。您可以使用 torchvision.datasets.ImageFolder 并在注释文件中提供边界框或创建自定义 Dataset 类。

# Define transformations (e.g., resizing, normalization)
transform = T.Compose([
    T.ToTensor(),
])
# Custom Dataset class or using an existing one
class CustomDataset(torch.utils.data.Dataset):
    def __init__(self, transforms=None):
        # Initialize dataset paths and annotations here
        self.transforms = transforms
        # Your dataset logic (image paths, annotations, etc.)

    def __getitem__(self, idx):
        # Load image
        img = ...  # Load your image here
        # Load corresponding bounding boxes and labels

        boxes = ...  # Load or define bounding boxes

        labels = ...  # Load or define labels

        # Create a target dictionary
        target = {}
        target["boxes"] = torch.tensor(boxes, dtype=torch.float32)
        target["labels"] = torch.tensor(labels, dtype=torch.int64)
        # Apply transforms
        if self.transforms is not None:
            img = self.transforms(img)
        return img, target
    def __len__(self):
        # Return the length of your dataset
        return len(self.data)

步骤5:设置数据加载器

# Load dataset
dataset = CustomDataset(transforms=transform)
# Split into train and validation sets
indices = torch.randperm(len(dataset)).tolist()
train_dataset = torch.utils.data.Subset(dataset, indices[:-50])
valid_dataset = torch.utils.data.Subset(dataset, indices[-50:])
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=4, shuffle=True, 
                                   collate_fn=lambda x: tuple(zip(*x)))
valid_loader = DataLoader(valid_dataset, batch_size=4, shuffle=False, 
                                    collate_fn=lambda x: tuple(zip(*x)))

步骤6:设置训练循环

现在设置优化器和训练循环。对于Faster R-CNN,通常使用 SGDAdam 作为优化器。

# Move model to GPU if available
device = torch.device('cuda') if torch.cuda.is_available() 
                               else torch.device('cpu')
model.to(device)

# Set up the optimizer
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, 
                                                   weight_decay=0.0005)
# Learning rate scheduler
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, 
                                                               gamma=0.1)
# Train the model
num_epochs = 10
for epoch in range(num_epochs):
    model.train()
    train_loss = 0.0

   # Training loop
    for images, targets in train_loader:
        images = list(image.to(device) for image in images)
        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]

        # Zero the gradients
        optimizer.zero_grad()

        # Forward pass
        loss_dict = model(images, targets)
        losses = sum(loss for loss in loss_dict.values())

        # Backward pass
        losses.backward()
        optimizer.step()
        train_loss += losses.item()

    # Update the learning rate
    lr_scheduler.step()
    print(f'Epoch: {epoch + 1}, Loss: {train_loss / len(train_loader)}')
print("Training complete!")

步骤7:评估模型

训练后,您可以在验证集上评估模型,或将其用于新图像的推理。

# Set the model to evaluation mode
model.eval()
# Test on a new image
with torch.no_grad():
    for images, targets in valid_loader:
        images = list(img.to(device) for img in images)
        predictions = model(images)
        # Example: print the bounding boxes and labels for the first image
        print(predictions[0]['boxes'])
        print(predictions[0]['labels'])

8.推理

要在新图像上运行推理,请执行以下操作:

import cv2
from PIL import Image
# Load image
img = Image.open("path/to/your/image.jpg")
# Apply the same transformation as for training
img = transform(img)
img = img.unsqueeze(0).to(device)
# Model prediction
model.eval()
with torch.no_grad():
    prediction = model([img])
# Print the predicted bounding boxes and labels
print(prediction[0]['boxes'])
print(prediction[0]['labels'])

https://i-blog.csdnimg.cn/direct/19a19b1d392944be90df72e4fa6b7b3d.png

**好了,这篇文章就介绍到这里,喜欢的小伙伴感谢给点个赞和关注,更多精彩内容持续更新~~

关于本篇文章大家有任何建议或意见,欢迎在评论区留言交流!**