import numpy as np


def filterBox(det0, det1):
    # det0为 (m1, 6) 矩阵
    # det1为 (m2, 6) 矩阵
    # 列方向上的6个元素代表x1, y1, x2, y2, conf(置信度), cls(类别)
    m, n = det0.size, det1.size
    if not m:
        return det0
    # 在det0的列方向加一个元素flag代表该目标框中心点是否在之前目标框内(0代表不在，其他代表在)
    flag = np.zeros([len(det0), 1])
    det0 = np.concatenate([det0, flag], axis=1)
    det0_copy = det0.copy()
    if not n:
        return det0
    # det0转成 (m1, m2, 7) 的矩阵
    # det1转成 (m1, m2, 6) 的矩阵
    # det0与det1在第3维方向上拼接(6 + 7 = 13)
    det0 = det0[:, np.newaxis, :].repeat(det1.shape[0], 1)
    det1 = det1[np.newaxis, ...].repeat(det0[0], 0)
    joint_det = np.concatenate((det1, det0), axis=2)
    # 分别求det0和det1的x1, y1, x2, y2(水平框的左上右下角点)
    x1, y1, x2, y2 = joint_det[..., 0], joint_det[..., 1], joint_det[..., 2], joint_det[..., 3]
    x3, y3, x4, y4 = joint_det[..., 6], joint_det[..., 7], joint_det[..., 8], joint_det[..., 9]
    x_c, y_c = (x3+x4)/2, (y3+y4)/2
    # 类别相同 & 中心点在上一帧的框内 判断为True
    mask = (joint_det[..., 5] == joint_det[..., 11]) & ((x_c >= x1) & (x_c <= x2) & (y_c >= y1) & (y_c <= y2))
    # res得出结果为该框中心点在上一帧框中出现的次数
    res = np.sum(mask, axis=1)
    # x1, y1, x2, y2, conf, cls, flag (flag代表当前框有多少个满足mask中条件)
    det0_copy[..., -1] = res

    return det0_copy




