本文简介一个numpy中的小trick,即用一个dtype=boolean的list作为mask来读取np.array
原理很简单,直接给示例:
array1 = np.array([1,2,3,4])
array2 = np.array([[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]])
mask = [True, False, True, False]
print(array1[mask])
print(array2[mask])
out:
[1 3]
[[ 1 2 3 4 5]
[11 12 13 14 15]]
然后再给一个实际场合下的例子(目标跟踪场景下,从detections_matrix中提取某一帧的detections)
# 得到给定frame_idx帧的所有detections返回为列表(bbox, confidence, feature)
def create_detections(detection_mat, frame_idx, min_height=0):
"""Create detections for given frame index from the raw detection matrix.
Parameters
----------
detection_mat : ndarray
Matrix of detections. The first 10 columns of the detection matrix are
in the standard MOTChallenge detection format. In the remaining columns
store the feature vector associated with each detection.
frame_idx : int
The frame index.
min_height : Optional[int]
A minimum detection bounding box height. Detections that are smaller
than this value are disregarded.
Returns
-------
List[tracker.Detection]
Returns detection responses at given frame index.
"""
frame_indices = detection_mat[:, 0].astype(np.int) # 每个detection的第一个元素为frame_id
mask = frame_indices == frame_idx # frame_id mask
detection_list = []
for row in detection_mat[mask]: # 利用mask选取detection_mat,对其进行遍历
bbox, confidence, feature = row[2:6], row[6], row[10:] # 提取detection信息
if bbox[3] < min_height:
continue
detection_list.append(Detection(bbox, confidence, feature))
return detection_list