1. 程式人生 > >獲取Faster RCNN最終候選框座標值

獲取Faster RCNN最終候選框座標值

經過之前的訓練,小魚對Faster RCNN網路實現檢測功能已經瞭解了一點,接下來就是利用網路的檢測結果實現多目標的跟蹤.這個專題就用來記錄一些實現跟蹤道路上的小知識點.

今天小魚分享的是:如何利用訓練好的網路得到測試圖片的候選框座標?

在執行~/py-faster-rcnn/tools/demo.py這個檔案時對測試集的目標進行了候選框的視覺化,也就是demo.py中的def vis_detections函式.這裡可以參考demo.py程式碼解析瞭解該程式碼的主要三個功能:候選框結果的視覺化;檢測目標框的獲取;引數的獲取

小魚就是從這裡得到最終的候選框座標,具體方法為:
1.分析視覺化什麼東西
視覺化函式為:

def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in
inds: bbox = dets[i, :4] score = dets[i, -1] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=3.5) ) ax.text(bbox[0
], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') ax.set_title(('{} detections with ' 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh), fontsize=14) plt.axis('off') plt.tight_layout() plt.draw()

從函式中可以得到是可視化了檢測的目標框bbox,並在每個目標框上表明檢測精度score.
2.找到視覺化的東西怎麼得到的
找出哪裡生成bbox,score,從視覺化函式的這兩個引數可以追溯到下一個函式中呼叫了視覺化函式,即demo函式:

def demo(net, image_name):
    """Detect object classes in an image using pre-computed object proposals."""

    # Load the demo image
    im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)
    im = cv2.imread(im_file)

    # Detect all object classes and regress object bounds
    timer = Timer()
    timer.tic()
    **scores, boxes = im_detect(net, im)**
    timer.toc()
    print ('Detection took {:.3f}s for '
           '{:d} object proposals').format(timer.total_time, boxes.shape[0])

    # Visualize detections for each class
    CONF_THRESH = 0.8
    NMS_THRESH = 0.3
    for cls_ind, cls in enumerate(CLASSES[1:]):
        cls_ind += 1 # because we skipped background
        cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
        cls_scores = scores[:, cls_ind]
        dets = np.hstack((cls_boxes,
                          cls_scores[:, np.newaxis])).astype(np.float32)
        keep = nms(dets, NMS_THRESH)
        dets = dets[keep, :]
        vis_detections(im, cls, dets, thresh=CONF_THRESH)

從這個函式中可以看到也有bbox,score,程式碼加粗部分.這裡又追溯到im_detect(net, im)函式,這個函數出現在~/py-faster-rcnn/lib/fast_rcnn/test.py中,我們就轉到這個函式,可以看到在im_detect(net, im)函式中有完整的計算bbox,score程式碼並return scores, pred_boxes.
這裡需要注意的是,在im_detect(net, im)函式中,182行加入列印程式碼:

print pred_boxes.shape
return scores, pred_boxes

即return程式碼上方直接打印出輸出bbox的維度,得到一個300*(4(K+1))的矩陣,k代表類別數.是最後輸入給Fast RCNN的300個候選框,不是我們想要的最終視覺化的候選框.
3.將這些需要的東西利用起來
找完之後,就開始各取所需.這裡小魚需要最終的候選框,那就是在視覺化中的候選框,我就只需要在~/py-faster-rcnn/tools/demo.py中加入print輸出指令即可,如在53行左右加入print bbox
最終的結果如下格式:

Demo for data/demo/00109.jpg
Detection took 0.142s for 300 object proposals
[ 1198.58422852  1014.32049561  1291.8581543   1123.05639648]
[ 675.29943848  634.83068848  766.93762207  724.48535156]
[ 1463.50634766   131.7862854   1548.50048828   223.23049927]
[ 1021.40447998   367.55706787  1138.07788086   479.88537598]
[ 1228.62817383   665.61010742  1330.26538086   781.8638916 ]
[ 1069.45117188   457.67938232  1159.40161133   542.62628174]
[ 588.99707031  251.40000916  685.6192627   361.50817871]
[ 1058.63061523   542.11383057  1131.95068359   612.54180908]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

每一行為~/data/demo/00109.jpg圖片中一個目標框的座標,總共多少行就證明該圖片上有多少個目標被檢測出來.