圖片輸入大小解析
1.單尺度輸入:
train_pipeline = [
......
dict(
type='Resize',
img_scale=(1333, 800),
keep_ratio=True),
......
dict(type='Pad', size_divisor=32),
]
實際輸入縮放計算方式:
max_long_edge = max(img_scale)
max_short_edge = min(img_scale)
# 取值方式: 大值/長邊 小值/短邊 誰的比值小 按誰來計算縮放比例
scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w))
keep_ratio表示是否保持圖片原始比例
keep_ratio=True時,通過上面計算方式找到縮放因子,最終
scale_w = int(w * float(scale_factor ) + 0.5),
scale_h = int(h * float(scale_factor ) + 0.5)
簡要概括就是: 利用 (小值/短邊) 和 (大值/長邊) 的比值小的爲基準,然後通過圖片比例來計算另一邊的長度。
舉例:
假設我的真實圖片大小是(400, 600),那麼按照上面的方式1333/600 = 2.22, 800/400=2,顯然,按照800的縮放係數更小,因此以800的縮放係數爲基準resize。那麼就有(400*2, 600*2) -> (800, 1200) ,此時shape(400, 600)的圖片,被resize成了 (800, 1200),這樣操作的好處是圖片在被resize的同時,儘量靠近原圖的大小。
但是,還沒有結束,在Resize之後,注意配置文件裏還有個Pad操作,將Resize之後的圖片Pad成size_divisor=32的倍數,具體邏輯是
pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor
pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor
經過pad操作之後,將(800,1200)變成了(800, 1216),這步操作的目的是避免卷積時,特徵損失。
keep_ratio=False時,直接按照config配置中的img_scale來縮放圖片,大值代表長邊,小值代表短邊,不會保持原有圖片比例。
2.多尺度輸入:
假設配置信息爲
train_pipeline = [
......
dict(
type='Resize',
img_scale=[(1333, 640), (1333, 800), (600,1080), (1200, 1000), (416,700)],
multiscale_mode='value',
# multiscale_mode='range',
keep_ratio=True),
......
]
多尺度輸入的訓練方式有兩種指定模式 value和range
value:
從img_scale中隨機一個turple,作爲img_scale
僞代碼:
# img_scales相當於config中的img_scale
num = len(img_scales)
scale_idx = np.random.randint(num )
img_scale = img_scales[scale_idx]
range:
long_edge: 每個turple中的大值,作爲一個集合,上例中的就是:
[1333,1333,1080,1200, 700]
short_edge: 每個turple中的大值,作爲一個集合,上例中的就是:
[640,800,600,1000, 416]
然後,從long_edge和short_edge中分別隨機一個值作爲新的img_scale,得到img_scale後,輸入大小計算方式同單尺度。
僞代碼:
# img_scales相當於config中的img_scale
long_edge = [max(s) for s in img_scales]
short_edge= [min(s) for s in img_scales]
l_edge = np.random.randint(long_edge)
s_edge = np.random.randint(short_edge)
img_scale = (l_edge, s_edge)
octave_base_scale
模型定義中用到參數,後續整理
# model settings
model = dict(
type='FasterRCNN', # model類型
pretrained='modelzoo://resnet50', # 預訓練模型:imagenet-resnet50
backbone=dict(
type='ResNet', # backbone類型
depth=50, # 網絡層數
num_stages=4, # resnet的stage數量
out_indices=(0, 1, 2, 3), # 輸出的stage的序號
frozen_stages=1, # 凍結的stage數量,即該stage不更新參數,-1表示所有的stage都更新參數
style='pytorch'), # 網絡風格:如果設置pytorch,則stride爲2的層是conv3x3的卷積層;如果設置caffe,則stride爲2的層是第一個conv1x1的卷積層
neck=dict(
type='FPN', # neck類型
in_channels=[256, 512, 1024, 2048], # 輸入的各個stage的通道數
out_channels=256, # 輸出的特徵層的通道數
num_outs=5), # 輸出的特徵層的數量
rpn_head=dict(
type='RPNHead', # RPN網絡類型
in_channels=256, # RPN網絡的輸入通道數
feat_channels=256, # 特徵層的通道數
anchor_scales=[8], # 生成的anchor的baselen,baselen = sqrt(w*h),w和h爲anchor的寬和高
anchor_ratios=[0.5, 1.0, 2.0], # anchor的寬高比
anchor_strides=[4, 8, 16, 32, 64], # 在每個特徵層上的anchor的步長(對應於原圖)
target_means=[.0, .0, .0, .0], # 均值
target_stds=[1.0, 1.0, 1.0, 1.0], # 方差
use_sigmoid_cls=True), # 是否使用sigmoid來進行分類,如果False則使用softmax來分類
bbox_roi_extractor=dict(
type='SingleRoIExtractor', # RoIExtractor類型
roi_layer=dict(type='RoIAlign', out_size=7, sample_num=2), # ROI具體參數:ROI類型爲ROIalign,輸出尺寸爲7,sample數爲2
out_channels=256, # 輸出通道數
featmap_strides=[4, 8, 16, 32]), # 特徵圖的步長
bbox_head=dict(
type='SharedFCBBoxHead', # 全連接層類型
num_fcs=2, # 全連接層數量
in_channels=256, # 輸入通道數
fc_out_channels=1024, # 輸出通道數
roi_feat_size=7, # ROI特徵層尺寸
num_classes=81, # 分類器的類別數量+1,+1是因爲多了一個背景的類別
target_means=[0., 0., 0., 0.], # 均值
target_stds=[0.1, 0.1, 0.2, 0.2], # 方差
reg_class_agnostic=False)) # 是否採用class_agnostic的方式來預測,class_agnostic表示輸出bbox時只考慮其是否爲前景,後續分類的時候再根據該bbox在網絡中的類別得分來分類,也就是說一個框可以對應多個類別
# model training and testing settings
train_cfg = dict(
rpn=dict(
assigner=dict(
type='MaxIoUAssigner', # RPN網絡的正負樣本劃分
pos_iou_thr=0.7, # 正樣本的iou閾值
neg_iou_thr=0.3, # 負樣本的iou閾值
min_pos_iou=0.3, # 正樣本的iou最小值。如果assign給ground truth的anchors中最大的IOU低於0.3,則忽略所有的anchors,否則保留最大IOU的anchor
ignore_iof_thr=-1), # 忽略bbox的閾值,當ground truth中包含需要忽略的bbox時使用,-1表示不忽略
sampler=dict(
type='RandomSampler', # 正負樣本提取器類型
num=256, # 需提取的正負樣本數量
pos_fraction=0.5, # 正樣本比例
neg_pos_ub=-1, # 最大負樣本比例,大於該比例的負樣本忽略,-1表示不忽略
add_gt_as_proposals=False), # 把ground truth加入proposal作爲正樣本
allowed_border=0, # 允許在bbox周圍外擴一定的像素
pos_weight=-1, # 正樣本權重,-1表示不改變原始的權重
smoothl1_beta=1 / 9.0, # 平滑L1係數
debug=False), # debug模式
rcnn=dict(
assigner=dict(
type='MaxIoUAssigner', # RCNN網絡正負樣本劃分
pos_iou_thr=0.5, # 正樣本的iou閾值
neg_iou_thr=0.5, # 負樣本的iou閾值
min_pos_iou=0.5, # 正樣本的iou最小值。如果assign給ground truth的anchors中最大的IOU低於0.3,則忽略所有的anchors,否則保留最大IOU的anchor
ignore_iof_thr=-1), # 忽略bbox的閾值,當ground truth中包含需要忽略的bbox時使用,-1表示不忽略
sampler=dict(
type='RandomSampler', # 正負樣本提取器類型
num=512, # 需提取的正負樣本數量
pos_fraction=0.25, # 正樣本比例
neg_pos_ub=-1, # 最大負樣本比例,大於該比例的負樣本忽略,-1表示不忽略
add_gt_as_proposals=True), # 把ground truth加入proposal作爲正樣本
pos_weight=-1, # 正樣本權重,-1表示不改變原始的權重
debug=False)) # debug模式
test_cfg = dict(
rpn=dict( # 推斷時的RPN參數
nms_across_levels=False, # 在所有的fpn層內做nms
nms_pre=2000, # 在nms之前保留的的得分最高的proposal數量
nms_post=2000, # 在nms之後保留的的得分最高的proposal數量
max_num=2000, # 在後處理完成之後保留的proposal數量
nms_thr=0.7, # nms閾值
min_bbox_size=0), # 最小bbox尺寸
rcnn=dict(
score_thr=0.05, nms=dict(type='nms', iou_thr=0.5), max_per_img=100) # max_per_img表示最終輸出的det bbox數量
# soft-nms is also supported for rcnn testing
# e.g., nms=dict(type='soft_nms', iou_thr=0.5, min_score=0.05) # soft_nms參數
)
# dataset settings
dataset_type = 'CocoDataset' # 數據集類型
data_root = 'data/coco/' # 數據集根目錄
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) # 輸入圖像初始化,減去均值mean並處以方差std,to_rgb表示將bgr轉爲rgb
data = dict(
imgs_per_gpu=2, # 每個gpu計算的圖像數量
workers_per_gpu=2, # 每個gpu分配的線程數
train=dict(
type=dataset_type, # 數據集類型
ann_file=data_root + 'annotations/instances_train2017.json', # 數據集annotation路徑
img_prefix=data_root + 'train2017/', # 數據集的圖片路徑
img_scale=(1333, 800), # 輸入圖像尺寸,最大邊1333,最小邊800
img_norm_cfg=img_norm_cfg, # 圖像初始化參數
size_divisor=32, # 對圖像進行resize時的最小單位,32表示所有的圖像都會被resize成32的倍數
flip_ratio=0.5, # 圖像的隨機左右翻轉的概率
with_mask=False, # 訓練時附帶mask
with_crowd=True, # 訓練時附帶difficult的樣本
with_label=True), # 訓練時附帶label
val=dict(
type=dataset_type, # 同上
ann_file=data_root + 'annotations/instances_val2017.json', # 同上
img_prefix=data_root + 'val2017/', # 同上
img_scale=(1333, 800), # 同上
img_norm_cfg=img_norm_cfg, # 同上
size_divisor=32, # 同上
flip_ratio=0, # 同上
with_mask=False, # 同上
with_crowd=True, # 同上
with_label=True), # 同上
test=dict(
type=dataset_type, # 同上
ann_file=data_root + 'annotations/instances_val2017.json', # 同上
img_prefix=data_root + 'val2017/', # 同上
img_scale=(1333, 800), # 同上
img_norm_cfg=img_norm_cfg, # 同上
size_divisor=32, # 同上
flip_ratio=0, # 同上
with_mask=False, # 同上
with_label=False, # 同上
test_mode=True)) # 同上
# optimizer
optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 優化參數,lr爲學習率,momentum爲動量因子,weight_decay爲權重衰減因子
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # 梯度均衡參數
# learning policy
lr_config = dict(
policy='step', # 優化策略
warmup='linear', # 初始的學習率增加的策略,linear爲線性增加
warmup_iters=500, # 在初始的500次迭代中學習率逐漸增加
warmup_ratio=1.0 / 3, # 起始的學習率
step=[8, 11]) # 在第8和11個epoch時降低學習率
checkpoint_config = dict(interval=1) # 每1個epoch存儲一次模型
# yapf:disable
log_config = dict(
interval=50, # 每50個batch輸出一次信息
hooks=[
dict(type='TextLoggerHook'), # 控制檯輸出信息的風格
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
# runtime settings
total_epochs = 12 # 最大epoch數
dist_params = dict(backend='nccl') # 分佈式參數
log_level = 'INFO' # 輸出信息的完整度級別
work_dir = './work_dirs/faster_rcnn_r50_fpn_1x' # log文件和模型文件存儲路徑
load_from = None # 加載模型的路徑,None表示從預訓練模型加載
resume_from = None # 恢復訓練模型的路徑
workflow = [('train', 1)] # 當前工作區名稱