深度學習一行一行敲faster rcnn-keras版(3.2,non_max_suppression_fast函數)
對源碼進行逐句解析,盡量說的很細緻。
歡迎各位看官捧場!
源碼地址:keras版本faster rcnn
想了解這篇文章的前後內容出門左拐:faster rcnn代碼理解-keras(目錄)
視頻目錄:深度學習一行一行敲faster rcnn-keras版(視頻目錄)
這章是關於--roi_helpers.py的non_max_suppression_fast函數。
該函數的作用是從所給定的所有預選框中選擇指定個數最合理的邊框。
函數輸入:
def non_max_suppression_fast(boxes, probs, overlap_thresh=0.9, max_boxes=300):n
輸入參數的含義:
- 框
- 每個框對應的概率大小(是否有物體)
- 重合度閾值
- 選取框的個數
函數輸出
return boxes, probsn
- 框(x1,y1,x2,y2)的形式
- 對應的概率
-------------------------------①------------------------------
if len(boxes) == 0:n return []nn# grab the coordinates of the bounding boxesnx1 = boxes[:, 0]ny1 = boxes[:, 1]nx2 = boxes[:, 2]ny2 = boxes[:, 3]nnnp.testing.assert_array_less(x1, x2)nnp.testing.assert_array_less(y1, y2)nn# if the bounding boxes integers, convert them to floats --n# this is important since well be doing a bunch of divisionsnif boxes.dtype.kind == "i":ntboxes = boxes.astype("float")n
對輸入的數據進行確認
- 不能為空
- 左上角的坐標小於右下角
- 數據類型的轉換
# initialize the list of picked indexestnpick = []nn# calculate the areasnarea = (x2 - x1) * (y2 - y1)nn# sort the bounding boxes nidxs = np.argsort(probs)n
- pick(拾取)用來存放邊框序號
- 計算框的面積
- probs按照概率從小到大排序【argsort函數返回的是數組值從小到大的索引值numpy中argsort函數用法】
list = [1, 2, 3, 44, 5, 6, 7,33, 9, 11]nidxs = np.argsort(list)nprint(idxs)n輸出:n[0 1 2 4 5 6 8 9 7 3]n
-------------------------------②------------------------------
接下來就是按照概率從大到小取出框,且框的重合度不可以高於overlap_thresh。代碼的思路是這樣的:
- 每一次取概率最大的框(即idxs最後一個)
- 刪除掉剩下的框中重和度高於overlap_thresh的框
- 直到取滿max_boxes為止
while len(idxs) > 0:n# grab the last index in the indexes list and add then# index value to the list of picked indexesnlast = len(idxs) - 1ni = idxs[last]npick.append(i)n
取出idxs隊列中最大概率框的序號,將其添加到pick中
# find the intersectionnnxx1_int = np.maximum(x1[i], x1[idxs[:last]])nyy1_int = np.maximum(y1[i], y1[idxs[:last]])nxx2_int = np.minimum(x2[i], x2[idxs[:last]])nyy2_int = np.minimum(y2[i], y2[idxs[:last]])nnww_int = np.maximum(0, xx2_int - xx1_int)nhh_int = np.maximum(0, yy2_int - yy1_int)nnarea_int = ww_int * hh_intn
計算取出來的框與剩下來的框區域的交集
# find the unionnarea_union = area[i] + area[idxs[:last]] - area_intnn# compute the ratio of overlapnoverlap = area_int/(area_union + 1e-6)nn# delete all indexes from the index list that havenidxs = np.delete(idxs, np.concatenate(([last],np.where(overlap > overlap_thresh)[0])))n
計算重疊率,然後刪除掉重疊率較高的位置【np.concatest],是因為最後一個位nate上[la置你已經用過了,就得將其從隊列中刪掉】
if len(pick) >= max_boxes:n breakn
當取足max_boxes框,停止循環
-------------------------------③------------------------------
boxes = boxes[pick].astype("int")nprobs = probs[pick]nreturn boxes, probsn
返回pick內存取的邊框和對應的概率
最後當然是附上測試的最終效果圖啦!
歡迎關注公眾號:huangxiaobai880
https://www.zhihu.com/video/918516609272913920推薦閱讀:
TAG:深度学习DeepLearning | 源码阅读 | 机器学习 |