class FasterRCNNBase(nn.Module):
廣義R-CNN的主要類。參數:支柱(nn.Module):項(nn.Module):roi_heads (n . module):從RPN擷取特性+建議并計算探測/遮罩。轉換(n . module):執行從輸入到feed的資料轉換該模型
def __init__(self, backbone, rpn, roi_heads, transform):-》參數重新指派給變量
super(FasterRCNNBase, self).__init__()
self.transform = transform
self.backbone = backbone
self.rpn = rpn
self.roi_heads = roi_heads
self._has_warned = False-》僅在torchscript模式下使用
@torch.jit.unused
def eager_outputs(self, losses, detections):-》訓練時傳回損失值測試時傳回檢測值
# type: (Dict[str, Tensor], List[Dict[str, Tensor]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
if self.training:
return losses
return detections
def forward(self, images, targets=None):-》前向傳播,參數:圖像(清單[張量]):待處理的圖像目标(list[Dict[張量]]):圖像中出現的地面真值盒(可選)傳回:結果(list[BoxList]或dict[張量]):模型的輸出。在訓練期間,它傳回一個包含損失的dict[張量]。在測試期間,它傳回包含其他字段的list[BoxList]比如“分數”、“标簽”和“mask”(用于mask R-CNN模型)。
if self.training and targets is None:-》傳值為空報錯
raise ValueError("In training mode, targets should be passed")
if self.training:
assert targets is not None
for target in targets: # 進一步判斷傳入的target的boxes參數是否符合規定
boxes = target["boxes"]-》取boxes值
if isinstance(boxes, torch.Tensor):
if len(boxes.shape) != 2 or boxes.shape[-1] != 4:
raise ValueError("Expected target boxes to be a tensor"-》報錯期望目标框是一個張量
"of shape [N, 4], got {:}.".format(
boxes.shape))
else:
raise ValueError("Expected target boxes to be of type "-》報錯預期的目标框是類型的
"Tensor, got {:}.".format(type(boxes)))
original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])-》擷取圖像資料集大小
for img in images:-》周遊圖像
val = img.shape[-2:]
assert len(val) == 2 # 防止輸入的是個一維向量
original_image_sizes.append((val[0], val[1]))-》擷取圖像大小
# original_image_sizes = [img.shape[-2:] for img in images]
images, targets = self.transform(images, targets) # 對圖像進行預處理
# print(images.tensors.shape)
features = self.backbone(images.tensors) # 将圖像輸入backbone得到特征圖
if isinstance(features, torch.Tensor): # 若隻在一層特征層上預測,将feature放入有序字典中,并編号為‘0’
features = OrderedDict([('0', features)]) # 若在多層特征層上預測,傳入的就是一個有序字典
# 将特征層以及标注target資訊傳入rpn中
proposals, proposal_losses = self.rpn(images, features, targets)
# 将rpn生成的資料以及标注target資訊傳入fast rcnn後半部分
detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)
# 對網絡的預測結果進行後處理(主要将bboxes還原到原圖像尺度上)
detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)
losses = {}
losses.update(detector_losses)-》更新檢測損失值
losses.update(proposal_losses)-》更新标簽損失值
if torch.jit.is_scripting():
if not self._has_warned:
warnings.warn("RCNN always returns a (Losses, Detections) tuple in scripting")-》輸出警告資訊
self._has_warned = True
return losses, detections
else:
return self.eager_outputs(losses, detections)
class TwoMLPHead(nn.Module):-》基于fpga的模型的标準頭參數:in_channels (int):輸入通道的數目representation_size (int):中間表示的大小
def __init__(self, in_channels, representation_size):
super(TwoMLPHead, self).__init__()
self.fc6 = nn.Linear(in_channels, representation_size)
self.fc7 = nn.Linear(representation_size, representation_size)
def forward(self, x):
x = x.flatten(start_dim=1)-》降維
x = F.relu(self.fc6(x))-》降維
x = F.relu(self.fc7(x))-》降維
return x
class FastRCNNPredictor(nn.Module):-》标準分類+邊界框回歸層R-CNN為快。參數:in_channels (int):輸入通道的數目
num_classes (int):輸出類的數量(包括背景)
def __init__(self, in_channels, num_classes):
super(FastRCNNPredictor, self).__init__()
self.cls_score = nn.Linear(in_channels, num_classes)
self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
def forward(self, x):
if x.dim() == 4:
assert list(x.shape[2:]) == [1, 1]
x = x.flatten(start_dim=1)
scores = self.cls_score(x)-》全連接配接神經網絡輸出分類預測值
bbox_deltas = self.bbox_pred(x)-》全連接配接神經網絡輸出目标框預測
return scores, bbox_deltas
class FasterRCNN(FasterRCNNBase):
def __init__(self, backbone, num_classes=None,
#轉換參數
min_size=800, max_size=1000, # 預處理resize時限制的最小尺寸與最大尺寸
image_mean=None, image_std=None, # 預處理normalize時使用的均值和方差
# RPN 參數
rpn_anchor_generator=None, rpn_head=None,
rpn_pre_nms_top_n_train=2000, rpn_pre_nms_top_n_test=1000, # rpn中在nms處理前保留的proposal數(根據score)
rpn_post_nms_top_n_train=2000, rpn_post_nms_top_n_test=1000, # rpn中在nms處理後保留的proposal數
rpn_nms_thresh=0.7, # rpn中進行nms處理時使用的iou門檻值
rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3, # rpn計算損失時,采集正負樣本設定的門檻值
rpn_batch_size_per_image=256, rpn_positive_fraction=0.5, # rpn計算損失時采樣的樣本數,以及正樣本占總樣本的比例
# 框參數
box_roi_pool=None, box_head=None, box_predictor=None,
# 移除低目标機率 fast rcnn中進行nms處理的門檻值 對預測結果根據score排序取前100個目标
box_score_thresh=0.05, box_nms_thresh=0.5, box_detections_per_img=100,
box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.5, # fast rcnn計算誤差時,采集正負樣本設定的門檻值
box_batch_size_per_image=512, box_positive_fraction=0.25, # fast rcnn計算誤差時采樣的樣本數,以及正樣本占所有樣本的比例
bbox_reg_weights=None):
if not hasattr(backbone, "out_channels"):
raise ValueError(
"backbone should contain an attribute out_channels"主幹應該包含一個out_channels屬性
"specifying the number of output channels (assumed to be the"指定輸出通道的數量(假設為所有的級别都一樣
"same for all the levels"
)
assert isinstance(rpn_anchor_generator, (AnchorsGenerator, type(None)))-》斷言
assert isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None)))
if num_classes is not None:
if box_predictor is not None:
raise ValueError("num_classes should be None when box_predictor "當box_predictor時,num_classes應該為None
"is specified")
else:
if box_predictor is None:
raise ValueError("num_classes should not be None when box_predictor "
"is not specified")
# 預測特征層的channels
out_channels = backbone.out_channels
# 若anchor生成器為空,則自動生成針對resnet50_fpn的anchor生成器
if rpn_anchor_generator is None:
anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
rpn_anchor_generator = AnchorsGenerator(
anchor_sizes, aspect_ratios
)
# 生成RPN通過滑動視窗預測網絡部分
if rpn_head is None:
rpn_head = RPNHead(
out_channels, rpn_anchor_generator.num_anchors_per_location()[0]
)
rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
# 定義整個RPN架構
rpn = RegionProposalNetwork(
rpn_anchor_generator, rpn_head,
rpn_fg_iou_thresh, rpn_bg_iou_thresh,
rpn_batch_size_per_image, rpn_positive_fraction,
rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_nms_thresh)
# 多尺度RoIAlign池化
if box_roi_pool is None:
box_roi_pool = MultiScaleRoIAlign(
featmap_names=['0', '1', '2', '3'], # 在哪些特征層進行roi pooling
output_size=[7, 7],
sampling_ratio=2)
# fast RCNN中roi pooling後的展平處理兩個全連接配接層部分
if box_head is None:
resolution = box_roi_pool.output_size[0] # 預設等于7
representation_size = 1024
box_head = TwoMLPHead(
out_channels * resolution ** 2,
representation_size
)
# 在box_head的輸出上預測部分
if box_predictor is None:
representation_size = 1024
box_predictor = FastRCNNPredictor(
representation_size,
num_classes)
# 将roi pooling, box_head以及box_predictor結合在一起
roi_heads = RoIHeads(
# box
box_roi_pool, box_head, box_predictor,
box_fg_iou_thresh, box_bg_iou_thresh,
box_batch_size_per_image, box_positive_fraction,
bbox_reg_weights,
box_score_thresh, box_nms_thresh, box_detections_per_img)
if image_mean is None:
image_mean = [0.485, 0.456, 0.406]
if image_std is None:
image_std = [0.229, 0.224, 0.225]
# 對資料進行标準化,縮放,打包成batch等處理部分
transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std)
super(FasterRCNN, self).__init__(backbone, rpn, roi_heads, transform)
import torch
from torch import nn
from collections import OrderedDict
from network_files.rpn_function import AnchorsGenerator, RPNHead, RegionProposalNetwork
from network_files.roi_head import RoIHeads
from torchvision.ops import MultiScaleRoIAlign
from torch.jit.annotations import Tuple, List, Dict, Optional
from torch import Tensor
import torch.nn.functional as F
import warnings
from network_files.transform import GeneralizedRCNNTransform
class FasterRCNNBase(nn.Module):
"""
Main class for Generalized R-CNN.
Arguments:
backbone (nn.Module):
rpn (nn.Module):
roi_heads (nn.Module): takes the features + the proposals from the RPN and computes
detections / masks from it.
transform (nn.Module): performs the data transformation from the inputs to feed into
the model
"""
def __init__(self, backbone, rpn, roi_heads, transform):
super(FasterRCNNBase, self).__init__()
self.transform = transform
self.backbone = backbone
self.rpn = rpn
self.roi_heads = roi_heads
# used only on torchscript mode
self._has_warned = False
@torch.jit.unused
def eager_outputs(self, losses, detections):
# type: (Dict[str, Tensor], List[Dict[str, Tensor]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
if self.training:
return losses
return detections
def forward(self, images, targets=None):
# type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
"""
Arguments:
images (list[Tensor]): images to be processed
targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)
Returns:
result (list[BoxList] or dict[Tensor]): the output from the model.
During training, it returns a dict[Tensor] which contains the losses.
During testing, it returns list[BoxList] contains additional fields
like `scores`, `labels` and `mask` (for Mask R-CNN models).
"""
if self.training and targets is None:
raise ValueError("In training mode, targets should be passed")
if self.training:
assert targets is not None
for target in targets: # 進一步判斷傳入的target的boxes參數是否符合規定
boxes = target["boxes"]
if isinstance(boxes, torch.Tensor):
if len(boxes.shape) != 2 or boxes.shape[-1] != 4:
raise ValueError("Expected target boxes to be a tensor"
"of shape [N, 4], got {:}.".format(
boxes.shape))
else:
raise ValueError("Expected target boxes to be of type "
"Tensor, got {:}.".format(type(boxes)))
original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])
for img in images:
val = img.shape[-2:]
assert len(val) == 2 # 防止輸入的是個一維向量
original_image_sizes.append((val[0], val[1]))
# original_image_sizes = [img.shape[-2:] for img in images]
images, targets = self.transform(images, targets) # 對圖像進行預處理
# print(images.tensors.shape)
features = self.backbone(images.tensors) # 将圖像輸入backbone得到特征圖
if isinstance(features, torch.Tensor): # 若隻在一層特征層上預測,将feature放入有序字典中,并編号為‘0’
features = OrderedDict([('0', features)]) # 若在多層特征層上預測,傳入的就是一個有序字典
# 将特征層以及标注target資訊傳入rpn中
proposals, proposal_losses = self.rpn(images, features, targets)
# 将rpn生成的資料以及标注target資訊傳入fast rcnn後半部分
detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)
# 對網絡的預測結果進行後處理(主要将bboxes還原到原圖像尺度上)
detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)
losses = {}
losses.update(detector_losses)
losses.update(proposal_losses)
if torch.jit.is_scripting():
if not self._has_warned:
warnings.warn("RCNN always returns a (Losses, Detections) tuple in scripting")
self._has_warned = True
return losses, detections
else:
return self.eager_outputs(losses, detections)
# if self.training:
# return losses
#
# return detections
class TwoMLPHead(nn.Module):
"""
Standard heads for FPN-based models
Arguments:
in_channels (int): number of input channels
representation_size (int): size of the intermediate representation
"""
def __init__(self, in_channels, representation_size):
super(TwoMLPHead, self).__init__()
self.fc6 = nn.Linear(in_channels, representation_size)
self.fc7 = nn.Linear(representation_size, representation_size)
def forward(self, x):
x = x.flatten(start_dim=1)
x = F.relu(self.fc6(x))
x = F.relu(self.fc7(x))
return x
class FastRCNNPredictor(nn.Module):
"""
Standard classification + bounding box regression layers
for Fast R-CNN.
Arguments:
in_channels (int): number of input channels
num_classes (int): number of output classes (including background)
"""
def __init__(self, in_channels, num_classes):
super(FastRCNNPredictor, self).__init__()
self.cls_score = nn.Linear(in_channels, num_classes)
self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
def forward(self, x):
if x.dim() == 4:
assert list(x.shape[2:]) == [1, 1]
x = x.flatten(start_dim=1)
scores = self.cls_score(x)
bbox_deltas = self.bbox_pred(x)
return scores, bbox_deltas
class FasterRCNN(FasterRCNNBase):
"""
Implements Faster R-CNN.
The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
image, and should be in 0-1 range. Different images can have different sizes.
The behavior of the model changes depending if it is in training or evaluation mode.
During training, the model expects both the input tensors, as well as a targets (list of dictionary),
containing:
- boxes (FloatTensor[N, 4]): the ground-truth boxes in [x1, y1, x2, y2] format, with values
between 0 and H and 0 and W
- labels (Int64Tensor[N]): the class label for each ground-truth box
The model returns a Dict[Tensor] during training, containing the classification and regression
losses for both the RPN and the R-CNN.
During inference, the model requires only the input tensors, and returns the post-processed
predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
follows:
- boxes (FloatTensor[N, 4]): the predicted boxes in [x1, y1, x2, y2] format, with values between
0 and H and 0 and W
- labels (Int64Tensor[N]): the predicted labels for each image
- scores (Tensor[N]): the scores or each prediction
Arguments:
backbone (nn.Module): the network used to compute the features for the model.
It should contain a out_channels attribute, which indicates the number of output
channels that each feature map has (and it should be the same for all feature maps).
The backbone should return a single Tensor or and OrderedDict[Tensor].
num_classes (int): number of output classes of the model (including the background).
If box_predictor is specified, num_classes should be None.
min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
image_mean (Tuple[float, float, float]): mean values used for input normalization.
They are generally the mean values of the dataset on which the backbone has been trained
on
image_std (Tuple[float, float, float]): std values used for input normalization.
They are generally the std values of the dataset on which the backbone has been trained on
rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
maps.
rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
considered as positive during training of the RPN.
rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
considered as negative during training of the RPN.
rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
for computing the loss
rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
of the RPN
box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
the locations indicated by the bounding boxes
box_head (nn.Module): module that takes the cropped feature maps as input
box_predictor (nn.Module): module that takes the output of box_head and returns the
classification logits and box regression deltas.
box_score_thresh (float): during inference, only return proposals with a classification score
greater than box_score_thresh
box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
box_detections_per_img (int): maximum number of detections per image, for all classes.
box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
considered as positive during training of the classification head
box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
considered as negative during training of the classification head
box_batch_size_per_image (int): number of proposals that are sampled during training of the
classification head
box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
of the classification head
bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
bounding boxes
"""
def __init__(self, backbone, num_classes=None,
# transform parameter
min_size=800, max_size=1000, # 預處理resize時限制的最小尺寸與最大尺寸
image_mean=None, image_std=None, # 預處理normalize時使用的均值和方差
# RPN parameters
rpn_anchor_generator=None, rpn_head=None,
rpn_pre_nms_top_n_train=2000, rpn_pre_nms_top_n_test=1000, # rpn中在nms處理前保留的proposal數(根據score)
rpn_post_nms_top_n_train=2000, rpn_post_nms_top_n_test=1000, # rpn中在nms處理後保留的proposal數
rpn_nms_thresh=0.7, # rpn中進行nms處理時使用的iou門檻值
rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3, # rpn計算損失時,采集正負樣本設定的門檻值
rpn_batch_size_per_image=256, rpn_positive_fraction=0.5, # rpn計算損失時采樣的樣本數,以及正樣本占總樣本的比例
# Box parameters
box_roi_pool=None, box_head=None, box_predictor=None,
# 移除低目标機率 fast rcnn中進行nms處理的門檻值 對預測結果根據score排序取前100個目标
box_score_thresh=0.05, box_nms_thresh=0.5, box_detections_per_img=100,
box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.5, # fast rcnn計算誤差時,采集正負樣本設定的門檻值
box_batch_size_per_image=512, box_positive_fraction=0.25, # fast rcnn計算誤差時采樣的樣本數,以及正樣本占所有樣本的比例
bbox_reg_weights=None):
if not hasattr(backbone, "out_channels"):
raise ValueError(
"backbone should contain an attribute out_channels"
"specifying the number of output channels (assumed to be the"
"same for all the levels"
)
assert isinstance(rpn_anchor_generator, (AnchorsGenerator, type(None)))
assert isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None)))
if num_classes is not None:
if box_predictor is not None:
raise ValueError("num_classes should be None when box_predictor "
"is specified")
else:
if box_predictor is None:
raise ValueError("num_classes should not be None when box_predictor "
"is not specified")
# 預測特征層的channels
out_channels = backbone.out_channels
# 若anchor生成器為空,則自動生成針對resnet50_fpn的anchor生成器
if rpn_anchor_generator is None:
anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
rpn_anchor_generator = AnchorsGenerator(
anchor_sizes, aspect_ratios
)
# 生成RPN通過滑動視窗預測網絡部分
if rpn_head is None:
rpn_head = RPNHead(
out_channels, rpn_anchor_generator.num_anchors_per_location()[0]
)
# 預設rpn_pre_nms_top_n_train = 2000, rpn_pre_nms_top_n_test = 1000,
# 預設rpn_post_nms_top_n_train = 2000, rpn_post_nms_top_n_test = 1000,
rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
# 定義整個RPN架構
rpn = RegionProposalNetwork(
rpn_anchor_generator, rpn_head,
rpn_fg_iou_thresh, rpn_bg_iou_thresh,
rpn_batch_size_per_image, rpn_positive_fraction,
rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_nms_thresh)
# Multi-scale RoIAlign pooling
if box_roi_pool is None:
box_roi_pool = MultiScaleRoIAlign(
featmap_names=['0', '1', '2', '3'], # 在哪些特征層進行roi pooling
output_size=[7, 7],
sampling_ratio=2)
# fast RCNN中roi pooling後的展平處理兩個全連接配接層部分
if box_head is None:
resolution = box_roi_pool.output_size[0] # 預設等于7
representation_size = 1024
box_head = TwoMLPHead(
out_channels * resolution ** 2,
representation_size
)
# 在box_head的輸出上預測部分
if box_predictor is None:
representation_size = 1024
box_predictor = FastRCNNPredictor(
representation_size,
num_classes)
# 将roi pooling, box_head以及box_predictor結合在一起
roi_heads = RoIHeads(
# box
box_roi_pool, box_head, box_predictor,
box_fg_iou_thresh, box_bg_iou_thresh,
box_batch_size_per_image, box_positive_fraction,
bbox_reg_weights,
box_score_thresh, box_nms_thresh, box_detections_per_img)
if image_mean is None:
image_mean = [0.485, 0.456, 0.406]
if image_std is None:
image_std = [0.229, 0.224, 0.225]
# 對資料進行标準化,縮放,打包成batch等處理部分
transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std)
super(FasterRCNN, self).__init__(backbone, rpn, roi_heads, transform)
https://github.com/WZMIAOMIAO/deep-learning-for-image-processing