Numpy trick:array[mask]

本文简介一个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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值