Faster RCNN minibatch.py解讀

minibatch.py 的功能是: Compute minibatch blobs for training a Fast R-CNN network. 與roidb不同的是, minibatch中存儲的并不是完整的整張圖像圖像,而是從圖像經過轉換后得到的四維blob以及從圖像中截取的proposals,以及與之對應的labels等

在整個faster rcnn訓練中,有兩處用到了minibatch.py,一處是rpn的開始數據輸入,另一處自然是fast rcnn的數據輸入。分別見stage1_rpn_train.pt與stage1_fast_rcnn_train.py的最前面,如下:
stage1_rpn_train.pt:

layer {name: 'input-data'type: 'Python'top: 'data'top: 'im_info'top: 'gt_boxes'python_param {module: 'roi_data_layer.layer'layer: 'RoIDataLayer'param_str: "'num_classes': 21"}
}

stage1_fast_rcnn_train.py:

name: "VGG_CNN_M_1024"
layer {name: 'data'type: 'Python'top: 'data'top: 'rois'top: 'labels'top: 'bbox_targets'top: 'bbox_inside_weights'top: 'bbox_outside_weights'python_param {module: 'roi_data_layer.layer'layer: 'RoIDataLayer'param_str: "'num_classes': 21"}
}

如上,共同的數據定義層為roi_data_layer.layer,在layer.py中,觀察前向傳播:

 def forward(self, bottom, top):"""Get blobs and copy them into this layer's top blob vector."""blobs = self._get_next_minibatch()for blob_name, blob in blobs.iteritems():top_ind = self._name_to_top_map[blob_name]# Reshape net's input blobstop[top_ind].reshape(*(blob.shape))# Copy data into net's input blobstop[top_ind].data[...] = blob.astype(np.float32, copy=False)def _get_next_minibatch(self):"""Return the blobs to be used for the next minibatch.If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in aseparate process and made available through self._blob_queue."""if cfg.TRAIN.USE_PREFETCH:return self._blob_queue.get()else:db_inds = self._get_next_minibatch_inds()minibatch_db = [self._roidb[i] for i in db_inds]return get_minibatch(minibatch_db, self._num_classes)

這時我們發現了get_minibatch,此函數出現在minibatch.py中。

在看這份代碼的時候,建議從get_minibatch開始。下面我們開始:
get_minibatch中,【輸入】:roidb是一個list,list中的每個元素是一個字典,每個字典對應一張圖片的信息,其中的主要信息有:


這里寫圖片描述

num_classes在pascal_voc中為21.

def get_minibatch(roidb, num_classes):"""Given a roidb, construct a minibatch sampled from it."""# 給定一個roidb,這個roidb中存儲的可能是多張圖片,也可能是單張或者多張圖片,num_images = len(roidb) # Sample random scales to use for each image in this batchrandom_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),size=num_images)assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \'num_images ({}) must divide BATCH_SIZE ({})'. \format(num_images, cfg.TRAIN.BATCH_SIZE)rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images  #這里在fast rcnn中,為128/2=64fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)#這里比例為0.25=1/4# Get the input image blob, formatted for caffe#將給定的roidb經過預處理(resize以及resize的scale),#然后再利用im_list_to_blob函數來將圖像轉換成caffe支持的數據結構,即 N * C * H * W的四維結構im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)blobs = {'data': im_blob}if cfg.TRAIN.HAS_RPN:#用在rpnassert len(im_scales) == 1, "Single batch only"assert len(roidb) == 1, "Single batch only"# gt boxes: (x1, y1, x2, y2, cls)gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]blobs['gt_boxes'] = gt_boxes#首先解釋im_info。對于一副任意大小PxQ圖像,傳入Faster RCNN前首先reshape到固定MxN,im_info=[M, N, scale_factor]則保存了此次縮放的所有信息。blobs['im_info'] = np.array( [[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],dtype=np.float32)else: # not using RPN ,用在fast rcnn# Now, build the region of interest and label blobsrois_blob = np.zeros((0, 5), dtype=np.float32)labels_blob = np.zeros((0), dtype=np.float32)bbox_targets_blob = np.zeros((0, 4 * num_classes), dtype=np.float32)bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)# all_overlaps = []for im_i in xrange(num_images):# 遍歷給定的roidb中的每張圖片,隨機組合sample of RoIs, 來生成前景樣本和背景樣本。# 返回包括每張圖片中的roi(proposal)的坐標,所屬的類別,bbox回歸目標,bbox的inside_weight等                        labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \= _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image,num_classes)# Add to RoIs blob# _sample_rois返回的im_rois并沒有縮放,所以這里要先縮放rois = _project_im_rois(im_rois, im_scales[im_i])batch_ind = im_i * np.ones((rois.shape[0], 1))rois_blob_this_image = np.hstack((batch_ind, rois))# 加上圖片的序號,共5列(index,x1,y1,x2,y2)rois_blob = np.vstack((rois_blob, rois_blob_this_image))# 將所有的盒子豎著擺放,如下:# n  x1  y1  x2  y2# 0  ..  ..  ..  ..# 0  ..  ..  ..  ..# :   :   :   :   :# 1   ..  ..  ..  ..# 1   ..  ..  ..  ..# Add to labels, bbox targets, and bbox loss blobslabels_blob = np.hstack((labels_blob, labels))# 水平向量,一維向量bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))# 將所有的bbox_targets_blob豎著擺放,如下: N*4k ,只有對應的類非0#   tx1  ty1  wx1  wy1   tx2  ty2  wx2  wy2    tx3  ty3  wx3  wy3#    0     0    0   0     0     0    0   0       0     0    0   0#    0     0    0   0     0.2   0.3  1.0 0.5     0     0    0   0#    0     0    0   0     0     0    0   0       0     0    0   0#    0     0    0   0     0     0    0   0       0.5   0.5  1.0  1.0#    0     0    0   0     0     0    0   0       0     0    0   0# 對于bbox_inside_blob ,與bbox_targets_blob 規模相同,只不過把上面非0的元素換成1即可。# all_overlaps = np.hstack((all_overlaps, overlaps))# For debug visualizations# _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps)blobs['rois'] = rois_blobblobs['labels'] = labels_blobif cfg.TRAIN.BBOX_REG:blobs['bbox_targets'] = bbox_targets_blobblobs['bbox_inside_weights'] = bbox_inside_blobblobs['bbox_outside_weights'] = \np.array(bbox_inside_blob > 0).astype(np.float32)
#對于bbox_outside_weights,此處看來與bbox_inside_blob 相同。return blobs

在 def get_minibatch(roidb, num_classes) 中調用此函數,傳進來的實參為單張圖像的roidb ,該函數主要功能是隨機組合sample of RoIs, 來生成前景樣本和背景樣本。這里很重要,
因為一般來說,生成的proposal背景類比較多,所以我們生成前景與背景的比例選擇為1:3,所以
這里每張圖片選取了1/4*64=16個前景,選取了3/4*64=48個背景box.


還有一個值得注意的是隨機采樣中,前景box可能會包含ground truth box.可能會參與分類,但是不會參加回歸,因為其回歸量為0. 是不是可以將

fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]

改為:

fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH && overlaps <1.0)[0]

會更合適呢,這樣就可以提取的全部是rpn的 proposal。

def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):"""Generate a random sample of RoIs comprising foreground and backgroundexamples."""# label = class RoI has max overlap withlabels = roidb['max_classes']overlaps = roidb['max_overlaps']rois = roidb['boxes']# Select foreground RoIs as those with >= FG_THRESH overlapfg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]# Guard against the case when an image has fewer than fg_rois_per_image# foreground RoIsfg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)# Sample foreground regions without replacementif fg_inds.size > 0:fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False)# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &(overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]# Compute number of background RoIs to take from this image (guarding# against there being fewer than desired)bg_rois_per_this_image = rois_per_image - fg_rois_per_this_imagebg_rois_per_this_image = np.minimum(bg_rois_per_this_image,bg_inds.size)# Sample foreground regions without replacementif bg_inds.size > 0:bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)# The indices that we're selecting (both fg and bg)keep_inds = np.append(fg_inds, bg_inds)# Select sampled values from various arrays:labels = labels[keep_inds]# Clamp labels for the background RoIs to 0labels[fg_rois_per_this_image:] = 0overlaps = overlaps[keep_inds]rois = rois[keep_inds]# 調用_get_bbox_regression_labels函數,生成bbox_targets 和 bbox_inside_weights,#它們都是N * 4K 的ndarray,N表示keep_inds的size,也就是minibatch中樣本的個數;bbox_inside_weights #也隨之生成bbox_targets, bbox_inside_weights = _get_bbox_regression_labels(roidb['bbox_targets'][keep_inds, :], num_classes)return labels, overlaps, rois, bbox_targets, bbox_inside_weights

def _get_bbox_regression_labels(bbox_target_data, num_classes):
該函數主要是獲取bbox_target_data中回歸目標的的4個坐標編碼作為bbox_targets,同時生成bbox_inside_weights,它們都是N * 4K 的ndarray,N表示keep_inds的size,也就是minibatch中樣本的個數。
bbox_target_data: N*5 ,每一行為(c,tx,ty,tw,th)

def _get_bbox_regression_labels(bbox_target_data, num_classes):"""Bounding-box regression targets are stored in a compact form in theroidb.This function expands those targets into the 4-of-4*K representation usedby the network (i.e. only one class has non-zero targets). The loss weightsare similarly expanded.Returns:bbox_target_data (ndarray): N x 4K blob of regression targetsbbox_inside_weights (ndarray): N x 4K blob of loss weights"""clss = bbox_target_data[:, 0]bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)inds = np.where(clss > 0)[0] # 取前景框for ind in inds:cls = clss[ind]start = 4 * clsend = start + 4bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTSreturn bbox_targets, bbox_inside_weights

對于roidb的圖像進行對應的縮放操作,并返回統一的blob數據,即 N * C * H * W(這里為2*3*600*1000)的四維結構

def _get_image_blob(roidb, scale_inds):"""Builds an input blob from the images in the roidb at the specifiedscales."""num_images = len(roidb)processed_ims = []im_scales = []for i in xrange(num_images):im = cv2.imread(roidb[i]['image'])  #shape:h*w*cif roidb[i]['flipped']:im = im[:, ::-1, :]   # 水平翻轉target_size = cfg.TRAIN.SCALES[scale_inds[i]]im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size,cfg.TRAIN.MAX_SIZE)im_scales.append(im_scale)processed_ims.append(im)# Create a blob to hold the input imagesblob = im_list_to_blob(processed_ims)return blob, im_scales

以上im_list_to_blob中將一系列的圖像轉化為標準的4維矩陣,進行了填0的補全操作,使得所有的圖片的大小相同。

prep_im_for_blob 進行尺寸變化,使得最小的邊長為target_size,最大的邊長不超過cfg.TRAIN.MAX_SIZE,并且返回縮放的比例。

def prep_im_for_blob(im, pixel_means, target_size, max_size):"""Mean subtract and scale an image for use in a blob."""im = im.astype(np.float32, copy=False)im -= pixel_meansim_shape = im.shapeim_size_min = np.min(im_shape[0:2])im_size_max = np.max(im_shape[0:2])im_scale = float(target_size) / float(im_size_min)# Prevent the biggest axis from being more than MAX_SIZEif np.round(im_scale * im_size_max) > max_size:im_scale = float(max_size) / float(im_size_max)im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,interpolation=cv2.INTER_LINEAR)return im, im_scale

所以對于原始的圖片,要縮放到標準的roidb的data的格式,實際上只需要乘以im_scale即可。
反之,如果回到原始的圖片,則只需要除以im_scale即可。

參考文獻

  1. http://blog.csdn.net/iamzhangzhuping/article/details/51393032
  2. faster-rcnn 之 基于roidb get_minibatch(數據準備操作)
  3. faster rcnn源碼解讀(六)之minibatch

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/258651.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/258651.shtml
英文地址,請注明出處:http://en.pswp.cn/news/258651.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

oracle精簡版_使用Entity Framework Core訪問數據庫(Oracle篇)

前言哇。。看看時間 真的很久很久沒寫博客了 將近一年了。最近一直在忙各種家中事務和公司的新框架 終于抽出時間來更新一波了。本篇主要講一下關于Entity Framework Core訪問oracle數據庫的采坑。。強調一下&#xff0c;本篇文章發布之前 關于Entity Framework Core訪問oracl…

interrupt、interrupted 、isInterrupted 區別

interrupt&#xff1a;調用方法&#xff0c;是線程處于中斷狀態&#xff0c;但是這個方法只是讓線程設置為中斷狀態&#xff0c;并不會真正的停止線程。支持線程中斷的方法就是在堅持線程中斷狀態&#xff0c;一旦線程中斷狀態被設置為中斷&#xff0c;就會拋出異常。interrupt…

java String部分源碼解析

String類型的成員變量 /** String的屬性值 */ private final char value[];/** The offset is the first index of the storage that is used. *//**數組被使用的開始位置**/private final int offset;/** The count is the number of characters in the String. *//**String中…

python在材料模擬中的應用_基于Python的ABAQUS二次開發及在板料快速沖壓成形模擬中的應用...

2009doi:1013969/j1issn1100722012120091041013基于Python的ABAQUS二次開發及在板料快速沖壓成形模擬中的應用(北京航空航天大學飛行器制造工程系,北京100191)吳向東劉志剛萬敏王文平黃霖摘要:采用Python腳本語言對ABAQUS的前處理模塊進行二次開發,討論了Python腳本在ABAQUS二次…

Doxygen簡介

&#xff08;轉自&#xff1a;http://www.cnblogs.com/liuliunumberone/archive/2012/04/10/2441391.html&#xff09; 一&#xff0e;什么是Doxygen? Doxygen 是一個程序的文件產生工具&#xff0c;可將程序中的特定批注轉換成為說明文件。通常我們在寫程序時&#xff0c;或多…

javascript之閉包理解以及應用場景

1 function fn(){2 var a 0;3 return function (){4 return a;5 } 6 }如上所示&#xff0c;上面第一個return返回的就是一個閉包&#xff0c;那么本質上說閉包就是一個函數。那么返回這個函數有什么用呢&#xff1f;那是因為這個函數可以調用到它外部的a…

faster rcnn學習之rpn、fast rcnn數據準備說明

在上文《 faster-rcnn系列學習之準備數據》,我們已經介紹了imdb與roidb的一些情況&#xff0c;下面我們準備再繼續說一下rpn階段和fast rcnn階段的數據準備整個處理流程。 由于這兩個階段的數據準備有些重合&#xff0c;所以放在一起說明。 我們并行地從train_rpn與train_fas…

sql server規范

常見的字段類型選擇 1.字符類型建議采用varchar/nvarchar數據類型2.金額貨幣建議采用money數據類型3.科學計數建議采用numeric數據類型4.自增長標識建議采用bigint數據類型 (數據量一大&#xff0c;用int類型就裝不下&#xff0c;那以后改造就麻煩了)5.時間類型建議采用為dat…

關于標準庫中的ptr_fun/binary_function/bind1st/bind2nd

http://www.cnblogs.com/shootingstars/archive/2008/11/14/860042.html 以前使用bind1st以及bind2nd很少&#xff0c;后來發現這兩個函數還挺好玩的&#xff0c;于是關心上了。在C Primer對于bind函數的描述如下&#xff1a;“綁定器binder通過把二元函數對象的一個實參綁定到…

CSS偽類

一、首字母的顏色字體寫法 p:first-letter 二、文本的特殊樣式設置 first-line css偽類可與css類配合使用 偽元素只能用于塊級元素 轉載于:https://www.cnblogs.com/boyblog/p/4623374.html

php 結構體_【開發規范】PHP編碼開發規范下篇:PSR-2編碼風格規范

之前的一篇文章是對PSR-1的基本介紹接下來是PSR-2 編碼風格規范&#xff0c;它是 PSR-1 基本代碼規范的繼承與擴展。PSR-1 和PSR-2是PHP開發中基本的編碼規范&#xff0c;大家其實都可以參考學習下&#xff0c;雖然說每個開發者都有自己熟悉的一套開發規范&#xff0c;但是我覺…

faster rcnn學習之rpn訓練全過程

上篇我們講解了rpn與fast rcnn的數據準備階段&#xff0c;接下來我們講解rpn的整個訓練過程。最后 講解rpn訓練完畢后rpn的生成。 我們順著stage1_rpn_train.pt的內容講解。 name: "VGG_CNN_M_1024" layer {name: input-datatype: Pythontop: datatop: im_infotop: …

BitMapData知識 轉

Bitmap和BitmapData 2010.5.25 smartblack整理 一、flash.display.Bitmap類及其兩個子類 1、繼承自DisplayObject&#xff0c;和InteractiveObject平級&#xff0c;所以無法調度鼠標事件&#xff0c;可以使用額外的包裝容器(Sprite)來實現偵聽。 2、只支持GIF、JPEG、PNG格式&a…

Android學習之高德地圖的通用功能開發步驟(二)

周一又來了&#xff0c;我就接著上次的開發步驟&#xff08;一&#xff09;來吧&#xff0c;繼續把高德地圖的相關簡單功能分享一下 上次寫到了第六步&#xff0c;接著寫第七步吧。 第七步&#xff1a;定位 地圖選點 路徑規劃 實時導航 以下是我的這個功能NaviMapActivity的…

Oracle中分區表中表空間屬性

Oracle中的分區表是Oracle中的一個很好的特性&#xff0c;可以把大表劃分成多個小表&#xff0c;從而提高對于該大表的SQL執行效率&#xff0c;而各個分區對應用又是透明的。分區表中的每個分區有獨立的存儲特性&#xff0c;包括表空間、PCT_FREE等。那分區表中的各分區表空間之…

期刊論文格式模板 電子版_期刊論文的框架結構

最近看到很火的一句話&#xff0c;若不是生活所迫&#xff0c;誰愿意把自己弄得一身才華。是否像極了正想埋頭苦寫卻毫無頭緒的你&#xff1f;發表期刊論文的用途 &#xff1a;1: 學校或者單位評獎&#xff0c;評優&#xff0c;推免等2&#xff1a;申領學位證(如畢業硬性要求&a…

faster rcnn學習之rpn 的生成

接著上一節《 faster rcnn學習之rpn訓練全過程》&#xff0c;假定我們已經訓好了rpn網絡&#xff0c;下面我們看看如何利用訓練好的rpn網絡生成proposal. 其網絡為rpn_test.pt # Enter your network definition here. # Use ShiftEnter to update the visualization. name: &q…

初學java之常用組件

1 2 import javax.swing.*;3 4 import java.awt.*;5 class Win extends JFrame6 {7 JTextField mytext; // 設置一個文本區8 JButton mybutton;9 JCheckBox mycheckBox[]; 10 JRadioButton myradio[]; 11 ButtonGroup group; //為一…

anaconda 安裝在c盤_最省心的Python版本和第三方庫管理——初探Anaconda

打算把公眾號和知乎專欄的文章搬運一點過來。 歷史文章可以去關注我的公眾號&#xff1a;不二小段&#xff0c;或者知乎&#xff1a;段小草。也歡迎來看我的視頻學Python↓↓↓跟不二學Python這篇文章可以作為Python入門的第一站可以結合這期視頻來看&#xff0c;基本上是這期視…

Iris recognition papers in the top journals in 2017

轉載自&#xff1a;https://kiennguyenstuff.wordpress.com/2017/10/05/iris-recognition-papers-in-the-top-journals-in-2017/ Top journals: – IEEE Transaction on Pattern Analysis and Machine Intelligence (PAMI) – Pattern Recognition (PR) – IEEE Transaction on…