分析
ds_utils.py 拥有的功能如下,输入的都是boxes:
- unique_boxes() 过滤大的重复框
- xywh_to_xyxy() 由xywh的格式转为xyxy格式
- xyxy_to_xywh() 由xyxy的格式转为xywh格式
- validate_boxes() 用于检测boxes是否超界
- filter_small_boxes() 用于过滤尺寸小于min_size的小框
难点主要是unique_boxes()的理解,其中数组v是让boxes合成一个非常大的数值,.astype(int)是精髓,他把合成的大数值转为一个int数值范围的数字,转换后的数值对于非常相近的大框是相等的。同理对小框因为不好超界,故没用:
主要代码:
# --------------------------------------------------------
# Fast/er R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import numpy as np
#unique_boxes函数,可以通过不同尺度因子的缩放,
# 从一系列的框中获取不重复框的数组指标,用于过滤重复框
#具体实现采用了hash的方法
def unique_boxes(boxes, scale=1.0):
"""Return indices of unique boxes."""
v = np.array([1, 1e3, 1e6, 1e9])
#box的4个坐标,与上面的v进行外积后转换为一个数,再进行判断。
hashes = np.round(boxes * scale).dot(v).astype(int)
_, index = np.unique(hashes, return_index=True)
return np.sort(index)
#xywh_to_xyxy,xyxy_to_xywh函数分别是框的两种表达形式的相互转换,
# 前者采用一个顶点坐标和长宽表示矩形,后者采用两个顶点坐标表示矩形,各有用途。
def xywh_to_xyxy(boxes):
"""Convert [x y w h] box format to [x1 y1 x2 y2] format."""
return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1))
def xyxy_to_xywh(boxes):
"""Convert [x1 y1 x2 y2] box format to [x y w h] format."""
return np.hstack((boxes[:, 0:2], boxes[:, 2:4] - boxes[:, 0:2] + 1))
#validata_boxes函数用于去除无效框,即超出边界或者左右,上下,不满足几何关系的点,
# 比如右边顶点的x坐标小于左边顶点。filer_small_boxes用于去掉过小的检测框。
def validate_boxes(boxes, width=0, height=0):
"""Check that a set of boxes are valid."""
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
assert (x1 >= 0).all()
assert (y1 >= 0).all()
assert (x2 >= x1).all()
assert (y2 >= y1).all()
assert (x2 < width).all()
assert (y2 < height).all()
#过滤尺寸小于min_size的框
def filter_small_boxes(boxes, min_size):
w = boxes[:, 2] - boxes[:, 0]
h = boxes[:, 3] - boxes[:, 1]
keep = np.where((w >= min_size) & (h > min_size))[0]
return keep