20241123

human_feature/onnx_infer_10.py
import os
import argparse
import glob
import cv2
import numpy as np
import onnxruntime
import tqdm
import pymysql
import time
import json
os.environ["CUDA_VISIBLE_DEVICES"] = "0"  # 使用 GPU 0
def get_connection():
    """创建并返回一个新的数据库连接。"""
    # 数据库连接信息
    host = 'localhost'
    user = 'root'
    password = '123456'
    database = 'video_streaming_database'
    return pymysql.connect(host=host, user=user, password=password, database=database)

def ensure_connection(connection):
    """确保连接有效。如果连接无效,则重新建立连接。"""
    if connection is None or not connection.open:
        print("Connection is invalid or closed. Reconnecting...")
        return get_connection()
    return connection

def npy_files_list(folder_path):
    """
    遍历文件夹中的所有 .npy 文件,将它们的内容合并并保存到一个新的 .npy 文件中。

    :param folder_path: 包含 .npy 文件的文件夹路径
    :param output_file: 合并后保存的 .npy 文件路径
    """
    # 存储所有 .npy 文件内容的列表
    all_data = []
    all_name = []
    # 遍历文件夹中的所有文件
    for file_name in os.listdir(folder_path):
        if file_name.endswith('.npy'):
            file_path = os.path.join(folder_path, file_name)
            # 加载 .npy 文件内容并添加到列表中
            data = np.load(file_path)
            all_data.append(data)
            all_name.append(file_name.split(".")[0])

    return all_data, all_name
    
def get_parser():
    parser = argparse.ArgumentParser(description="onnx model inference")

    parser.add_argument(
        "--model-path",
        default=R"/home/hitsz/yk_workspace/Yolov5_track/weights/sbs_r50_0206_export_params_True.onnx",
        help="onnx model path"
    )
    parser.add_argument(
        "--input",
        default="/home/hitsz/yk_workspace/Yolov5_track/test_4S_videos/test_yk1_det3/save_crops/test_yk1/person/1/*jpg",
        nargs="+",
        help="A list of space separated input images; "
             "or a single glob pattern such as 'directory/*.jpg'",
    )
    parser.add_argument(
        "--output",
        default='/home/hitsz/yk_workspace/Yolov5_track/02_output_det/onnx_output',
        help='path to save the output features'
    )
    parser.add_argument(
        "--height",
        type=int,
        default=384,
        help="height of image"
    )
    parser.add_argument(
        "--width",
        type=int,
        default=128,
        help="width of image"
    )
    return parser

def preprocess(image_path, image_height, image_width):
    original_image = cv2.imread(image_path)
    norm_mean = np.array([0.485, 0.456, 0.406])
    norm_std = np.array([0.229, 0.224, 0.225])
    normalized_img = (original_image / 255.0 - norm_mean) / norm_std
    original_image = normalized_img[:, :, ::-1]
    img = cv2.resize(original_image, (image_width, image_height), interpolation=cv2.INTER_CUBIC)
    img = img.astype("float32").transpose(2, 0, 1)[np.newaxis]  # (1, 3, h, w)
    return img

def normalize(nparray, order=2, axis=-1):
    """Normalize a N-D numpy array along the specified axis."""
    norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
    return nparray / (norm + np.finfo(np.float32).eps)

if __name__ == "__main__":
    args = get_parser().parse_args()

    # 配置数据库连接
    db_config = {
        'host': 'localhost',
        'user': 'root',
        'password': '123456',
        'database': 'video_streaming_database',
        'charset': 'utf8mb4',
    }

    # 定义批处理大小
    batch_size = 500
    pre_end_id = 1
    # 连接到数据库
    connection = pymysql.connect(**db_config)
    # 指定使用 GPU(CUDA Execution Provider)
    ort_sess = onnxruntime.InferenceSession(args.model_path, providers=['CUDAExecutionProvider'])
    # 使用示例
    folder_path = "/home/hitsz/yk_workspace/Yolov5_track/db_tools/human_feature/deature_npy"  # 替换为包含 .npy 文件的文件夹路径
    all_features, all_names = npy_files_list(folder_path)
    print("Providers being used:", ort_sess.get_providers())
    input_name = ort_sess.get_inputs()[0].name
    while True:
        connection = ensure_connection(connection)
        try:
            with connection.cursor() as cursor:
                # 获取自增ID的最大值
                start_time = time.time()
                cursor.execute("SELECT MAX(id) FROM new_detection_tracking_results_1")
                max_id = cursor.fetchone()[0]
                result = cursor.fetchone()  # 获取查询结果的第一行
                # 获取ID前面100条数据
                if max_id is not None:
                    start_id = max(pre_end_id, max_id - batch_size)
                    end_id = max(pre_end_id, max_id)
                    cursor.execute(f"SELECT crop_image_path FROM new_detection_tracking_results_1 WHERE id <= {end_id} AND id > {start_id}")
                    batch = cursor.fetchall()                    
                    connection.commit()
                    data = []
                    for result in batch:
 
                        crop_image_path = result[0]  # 假设crop_image_path是第一个字段
                        name_json_output_path = os.path.join(crop_image_path.split("/")[0], crop_image_path.split("/")[-1].split("_")[0] + "_" + crop_image_path.split("/")[-1].split("_")[1]+ "_track_name.json")
                        if not os.path.exists(crop_image_path[:-4] + ".jpg"):
                            continue
                        image = preprocess(crop_image_path[:-4] + ".jpg", args.height, args.width)
                        feat = ort_sess.run(None, {input_name: image})[0]
                        all_feature_distances = []
                        for feature in all_features:
                            # 假设 query_feats 和 gallery_feats 是 2048 维的 NumPy 数组
                            query_feats = feature  # m x 2048
                            gallery_feats = feat  # n x 2048
                            # 计算两个特征矩阵的形状
                            m, n = query_feats.shape[0], gallery_feats.shape[0]
                            # 计算距离矩阵
                            distmat = np.sum(np.square(query_feats), axis=1, keepdims=True).repeat(n, axis=1) + \
                                    np.sum(np.square(gallery_feats), axis=1, keepdims=True).repeat(m, axis=1).T
                            distmat = distmat - 2 * np.dot(query_feats, gallery_feats.T)
                            # 取最小距离
                            distance = np.min(distmat)
                            all_feature_distances.append(distance)
                        # 找到最小值
                        min_value = min(all_feature_distances)
                        # 获取最小值对应的索引
                        min_index = all_feature_distances.index(min_value)
                        if min_value < 175.0:
                            name = all_names[min_index]
                            id = crop_image_path.split("_")[-6]
                            data_dict = {id:str(name) + "_" + str(int(min_value))}
                            if os.path.exists(name_json_output_path):
                                with open(name_json_output_path, 'r') as json_file:
                                    try:
                                        existing_data = json.load(json_file)
                                        if not isinstance(existing_data, dict):
                                            existing_data = {}
                                    except json.JSONDecodeError:
                                        existing_data = {}
                            else:
                                existing_data = {}

                            data_dict = {id: str(name) + "_" + str(int(min_value))}
                            existing_data.update(data_dict)
                            with open(name_json_output_path, 'w') as json_file:
                                json.dump(existing_data, json_file, indent=4)

                        else:
                            name = ""
                    end_time = time.time()  
                    runtime = end_time - start_time
                    pre_end_id = end_id
                    print(f"起始ID:{start_id}   结束帧:{end_id}    处理ID数:{end_id - start_id}     程序运行时间:{runtime}秒")
                    if end_time - start_time > 10:
                        end_time = time.time()  
                        print(f"总时间{end_time - start_time}秒")
                        print("开始下一轮访问数据库\n")
                        continue
                    else:
                        print("休眠:  " + str(min(10, 10 - end_time + start_time)) + "秒\n")
                        time.sleep(min(10, 10 - end_time + start_time))
                    # 记录结束时间  
                    end_time = time.time()  
                    # 计算并打印运行时间  
                    print(f"总时间{end_time - start_time}秒")
                    print("开始下一轮访问数据库\n")
                else:
                    connection.commit()
                    time.sleep(1)
        except:
            print("ERROR...")

byte_tracker_new_1.py
import numpy as np
from collections import deque
import os
import os.path as osp
import copy
import torch
import torch.nn.functional as F

from yolov5.utils.general import xywh2xyxy, xyxy2xywh


from trackers.bytetrack.kalman_filter import KalmanFilter
from trackers.bytetrack import matching
from trackers.bytetrack.basetrack import BaseTrack, TrackState

###########以下为跟踪算法改进简介###################################
##改进1说明:将宽高比小于某个阈值如0.35,的检测框补全到宽高比0.35的正常框用来进行跟踪匹配,
##同时保留原始的检测框以供输出,原始检测框保存于tlwh_ori

##改进2说明:将输入到卡尔曼滤波器的点由检测框的中心点改为检测框的上边缘中心点
#################分割线########################

##改进3说明:对所有传递进来的检测框进行过滤,去除宽度占比小于屏幕百分之2的框
##改进3需要修改外层track.py配合,用于传递屏幕像素值,
#需要在track.py文件的大约595行代码:tracker_list.append(tracker, )的上一行添加一行以下代码:
#tracker.wh = (dataset.cap.get(cv2.CAP_PROP_FRAME_WIDTH),dataset.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
#将画面宽高wh传给跟踪器
#################分割线########################

class STrack(BaseTrack):
    shared_kalman = KalmanFilter()
    ####“改进1”########################
    ## 原来为def __init__(self, tlwh, score, cls):,
    ##新增初始化参数tlwh_ori
    def __init__(self, tlwh,tlwh_ori, score, cls):
    #####改进结束线##########################
        # wait activate
        self._tlwh = np.asarray(tlwh, dtype=np.float32)
        ####“改进1”########################
        ##新增初始化变量_tlwh_ori代码 _tlwh_ori保存
        self._tlwh_ori = np.asarray(tlwh_ori, dtype=np.float32)
        ###改进结束线############################
        self.kalman_filter = None
        self.mean, self.covariance = None, None
        self.is_activated = False

        self.score = score
        self.tracklet_len = 0
        self.cls = cls

    def predict(self):
        mean_state = self.mean.copy()
        if self.state != TrackState.Tracked:
            mean_state[7] = 0
        self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)

    @staticmethod
    def multi_predict(stracks):
        if len(stracks) > 0:
            multi_mean = np.asarray([st.mean.copy() for st in stracks])
            multi_covariance = np.asarray([st.covariance for st in stracks])
            for i, st in enumerate(stracks):
                if st.state != TrackState.Tracked:
                    multi_mean[i][7] = 0
            multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
            for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
                stracks[i].mean = mean
                stracks[i].covariance = cov

    def activate(self, kalman_filter, frame_id):
        """Start a new tracklet"""
        self.kalman_filter = kalman_filter
        self.track_id = self.next_id()
        ###########改进2########################
        ####原始代码为: 
        #self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))
        self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_tcah(self._tlwh))
        #####改进结束线##############################################
        self.tracklet_len = 0
        self.state = TrackState.Tracked
        if frame_id == 1:
            self.is_activated = True
        # self.is_activated = True
        self.frame_id = frame_id
        self.start_frame = frame_id
        ##########改进2############################
        ##原始代码为:
        #def re_activate(self, new_track, frame_id, new_id=False):
        # self.mean, self.covariance = self.kalman_filter.update(
        #     self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
        # )
        #此处修改传递的参数为上框的边缘顶点而非框中心tcah表示top center aspect-ratio high
    def re_activate(self, new_track, frame_id, new_id=False): 
        self.mean, self.covariance = self.kalman_filter.update(
            self.mean, self.covariance, self.tlwh_to_tcah(new_track.tlwh)
        )
        ##########改进结束线####################
        self._tlwh_ori = new_track._tlwh_ori
        self.tracklet_len = 0
        self.state = TrackState.Tracked
        self.is_activated = True
        self.frame_id = frame_id
        if new_id:
            self.track_id = self.next_id()
        self.score = new_track.score
        self.cls = new_track.cls

    def update(self, new_track, frame_id):
        """
        Update a matched track
        :type new_track: STrack
        :type frame_id: int
        :type update_feature: bool
        :return:
        """
        self.frame_id = frame_id
        self.tracklet_len += 1
        # self.cls = cls

        new_tlwh = new_track.tlwh
        ######改进2######################
        ####原代码:
        # self.mean, self.covariance = self.kalman_filter.update(
            # self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
        self.mean, self.covariance = self.kalman_filter.update(
            self.mean, self.covariance, self.tlwh_to_tcah(new_tlwh))
        ########改进结束线###############

        ######改进1######################
        #####新增代码,保存原始框位置
        self._tlwh_ori = new_track._tlwh_ori
        ######改进结束线###############
        self.state = TrackState.Tracked
        self.is_activated = True

        self.score = new_track.score

    @property
    # @jit(nopython=True)
    def tlwh(self):
        """Get current position in bounding box format `(top left x, top left y,
                width, height)`.
        """
        if self.mean is None:
            return self._tlwh.copy()
        ret = self.mean[:4].copy()
        ret[2] *= ret[3]
        ###########改进2#########
        ######原代码:
        ####ret[:2] -= ret[2:] / 2
        ####原代码将框的中心点转换为左上角顶点,新代码将上边缘中心点转为左上角顶点
        ret[0] -= ret[2] / 2
        ######改进结束线##############
        return ret
    

    ###########改进1#########
    ##下列函数为新增函数,目的是输出保存的原始检测框
    @property
    # @jit(nopython=True)
    def tlwh_ori(self):
        ret = self._tlwh_ori.copy()
        # ret[:2] -= ret[2:] / 2
        return ret
    ######改进结束线##################
    @property
    # @jit(nopython=True)
    def tlbr(self):
        """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
        `(top left, bottom right)`.
        """
        ret = self.tlwh.copy()
        ret[2:] += ret[:2]
        return ret

    @staticmethod
    # @jit(nopython=True)
    def tlwh_to_xyah(tlwh):
        """Convert bounding box to format `(center x, center y, aspect ratio,
        height)`, where the aspect ratio is `width / height`.
        """
        ret = np.asarray(tlwh).copy()
        ret[:2] += ret[2:] / 2
        ret[2] /= ret[3]
        return ret
    ###########改进2#####################
    ##下列函数为新增函数,目的是将左上角顶点转换为上边缘中点
    @staticmethod
    # @jit(nopython=True)
    def tlwh_to_tcah(tlwh):
        """Convert bounding box to format `(topcenter x, topcenter y, aspect ratio,
        height)`, where the aspect ratio is `width / height`.
        """
        ret = np.asarray(tlwh).copy()
        ret[0] += ret[2] / 2
        ret[2] /= ret[3]
        return ret
    ########改进结束线#################
    def to_xyah(self):
        return self.tlwh_to_xyah(self.tlwh)

    @staticmethod
    # @jit(nopython=True)
    def tlbr_to_tlwh(tlbr):
        ret = np.asarray(tlbr).copy()
        ret[2:] -= ret[:2]
        return ret

    @staticmethod
    # @jit(nopython=True)
    def tlwh_to_tlbr(tlwh):
        ret = np.asarray(tlwh).copy()
        ret[2:] += ret[:2]
        return ret

    def __repr__(self):
        return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)


class BYTETracker(object):
    def __init__(self, track_thresh=0.45, match_thresh=0.8, track_buffer=25, frame_rate=30):
        self.tracked_stracks = []  # type: list[STrack]
        self.lost_stracks = []  # type: list[STrack]
        self.removed_stracks = []  # type: list[STrack]

        self.frame_id = 0
        self.track_buffer=track_buffer
        
        self.track_thresh = track_thresh
        #self.inner_polygon=None
        #####改进3#################
        ###新增宽高属性,默认为(1920,1080),初始化跟踪器时传入
        self.wh = (1920,1080)
        #######改进结束线############################
        self.match_thresh = match_thresh
        self.det_thresh = track_thresh + 0.1
        self.buffer_size = int(frame_rate / 25.0 * track_buffer)
        self.max_time_lost = self.buffer_size
        self.kalman_filter = KalmanFilter()

    ###########改进3#########
    ##下列函数为新增函数,removeSmallDets函数用于移除宽度小于百分之2的框
    def removeSmallDets(self,dets):
        new_ind=[]
        for i,det in enumerate(dets):
            xyxys = det[0:4]
            xywh = xyxy2xywh(xyxys)
            if xywh[2]/self.wh[0]>=0.02:
                new_ind.append(i)
        return new_ind
    ########改进结束线#################

    ###########改进1###################
    ##下列函数为新增函数,
    ##correct_det_xywh函数用于对宽高比不符合要求的框进行补全,检测阈值为0.35,补全为0.33
    def correct_det_xywh(self,dets):
        det_correc = dets.clone()
        for i,det in enumerate(dets):
            det_copy = det.clone()
            if det[2]/det[3]>0.35:
                det_copy[1] = det_copy[1] + (det_copy[2]/0.33-det_copy[3])/2
                det_copy[3] = det_copy[2]/0.33
            
            det_correc[i]=det_copy
        return det_correc
    ############改进结束线#############################

    def update(self, dets, _):
        ########改进3##############
        ###新增如下2行代码
        ###过滤宽度太小的框
        new_ind = self.removeSmallDets(dets)
        dets = dets[new_ind]
        #########改进结束线#############
        self.frame_id += 1
        activated_starcks = []
        refind_stracks = []
        lost_stracks = []
        removed_stracks = []

        xyxys = dets[:, 0:4]
        xywh = xyxy2xywh(xyxys)
        confs = dets[:, 4]
        clss = dets[:, 5]
        
        classes = clss.numpy()
        xyxys = xyxys.numpy()
        confs = confs.numpy()
        remain_inds = confs > self.track_thresh
        inds_low = confs > 0.1
        inds_high = confs < self.track_thresh

        inds_second = np.logical_and(inds_low, inds_high)
        #########改进1##############
        #### 原代码为:
        #dets_second = xywh[inds_second]
        #dets = xywh[remain_inds]
        ####先保存原始检测框,再对原始检测框进行修正
        ####修改为:
        dets_second_ori = xywh[inds_second]
        dets_ori = xywh[remain_inds]
        dets_second = self.correct_det_xywh(dets_second_ori)
        dets = self.correct_det_xywh(dets_ori)
        ##########改进结束线################

        scores_keep = confs[remain_inds]
        scores_second = confs[inds_second]
        
        clss_keep = classes[remain_inds]
        clss_second = classes[inds_second]
        

        if len(dets) > 0:
            '''Detections'''
            #######改进1############
            ##原始代码为:
            #detections = [STrack(xyxy, s, c) for (xyxy, s, c) in zip(dets, scores_keep, clss_keep)]
            #这里将Stack的输出增加一个xyxy_ori,保存原始的检测框(高置信度)
            detections = [STrack(xyxy,xyxy_ori, s, c) for (xyxy,xyxy_ori, s, c) in zip(dets,dets_ori, scores_keep, clss_keep)]
            #########改进结束线##############
        else:
            detections = []

        ''' Add newly detected tracklets to tracked_stracks'''
        unconfirmed = []
        tracked_stracks = []  # type: list[STrack]
        for track in self.tracked_stracks:
            if not track.is_activated:
                unconfirmed.append(track)
            else:
                tracked_stracks.append(track)

        ''' Step 2: First association, with high score detection boxes'''
        # 将track_stracks和lost_stracks合并得到track_pool
        strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
        STrack.multi_predict(strack_pool)
        # 计算strack_pool(当前帧的预测框和之前未匹配到轨迹的bbox)和detections的iou_distance(代价矩阵)
        # detections是当前帧的bbox
        dists = matching.iou_distance(strack_pool, detections)
        #if not self.args.mot20:
        dists = matching.fuse_score(dists, detections)
        matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.match_thresh)
        # 遍历matches,如果state为Tracked,调用update方法,并加入到activated_stracks,否则调用re_activate,并加入refind_stracks
        # matches = [itracked, idet] itracked指的是轨迹的索引,idet 指的是当前目标框的索引,意思是第几个轨迹匹配第几个目标框
        for itracked, idet in matches:
            track = strack_pool[itracked]
            det = detections[idet]
            if track.state == TrackState.Tracked:
                track.update(det, self.frame_id)
                activated_starcks.append(track)
            else:
                track.re_activate(det, self.frame_id, new_id=False)
                refind_stracks.append(track)

        ''' Step 3: Second association, with low score detection boxes'''
        # association the untrack to the low score detections
        if len(dets_second) > 0:
            '''Detections'''
            #######改进1############
            ##原始代码为:
            #detections_second = [STrack(xywh, s, c) for (xywh, s, c) in zip(dets_second, scores_second, clss_second)]
            ####与上面一样,新增xyxy_ori属性保存原始检测框(低置信度)
            detections_second = [STrack(xyxy,xyxy_ori, s, c) for (xyxy,xyxy_ori, s, c) in zip(dets,dets_ori, scores_keep, clss_keep)]
            ##########改进结束线##############################
        else:
            detections_second = []
        r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
        dists = matching.iou_distance(r_tracked_stracks, detections_second)
        #####修改低置信度匹配阈值######
        #原始为0.5修改为0.7:
        #matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.5)
        matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.7)
        ###########改进结束线##############
        for itracked, idet in matches:
            track = r_tracked_stracks[itracked]
            det = detections_second[idet]
            if track.state == TrackState.Tracked:
                track.update(det, self.frame_id)
                activated_starcks.append(track)
            else:
                track.re_activate(det, self.frame_id, new_id=False)
                refind_stracks.append(track)

        for it in u_track:
            track = r_tracked_stracks[it]
            if not track.state == TrackState.Lost:
                track.mark_lost()
                lost_stracks.append(track)

        '''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
        detections = [detections[i] for i in u_detection]
        dists = matching.iou_distance(unconfirmed, detections)
        dists = matching.fuse_score(dists, detections)
        matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
        for itracked, idet in matches:
            unconfirmed[itracked].update(detections[idet], self.frame_id)
            activated_starcks.append(unconfirmed[itracked])
        for it in u_unconfirmed:
            track = unconfirmed[it]
            track.mark_removed()
            removed_stracks.append(track)

        """ Step 4: Init new stracks"""
        for inew in u_detection:
            track = detections[inew]
            if track.score < self.det_thresh:
                continue
            track.activate(self.kalman_filter, self.frame_id)
            activated_starcks.append(track)
        """ Step 5: Update state"""
        for track in self.lost_stracks:
            if self.frame_id - track.end_frame > self.max_time_lost:
                track.mark_removed()
                removed_stracks.append(track)
        self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
        self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks)
        self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks)
        self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks)
        self.lost_stracks.extend(lost_stracks)
        self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks)
        self.removed_stracks.extend(removed_stracks)
        self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
        # get scores of lost tracks
        output_stracks = [track for track in self.tracked_stracks if track.is_activated]
        outputs = []
        for t in output_stracks:
            output= []
            #############改进1##################
            ####输出原始检测框
            ##原代码为:
            # tlwh = t.tlwh
            tlwh = t.tlwh_ori
            #############改进结束线##################
            tid = t.track_id
            tlwh = np.expand_dims(tlwh, axis=0)
            xyxy = xywh2xyxy(tlwh)
            xyxy = np.squeeze(xyxy, axis=0)
            output.extend(xyxy)
            output.append(tid)
            output.append(t.cls)
            output.append(t.score)
            outputs.append(output)
        return outputs

def joint_stracks(tlista, tlistb):
    exists = {}
    res = []
    for t in tlista:
        exists[t.track_id] = 1
        res.append(t)
    for t in tlistb:
        tid = t.track_id
        if not exists.get(tid, 0):
            exists[tid] = 1
            res.append(t)
    return res


def sub_stracks(tlista, tlistb):
    stracks = {}
    for t in tlista:
        stracks[t.track_id] = t
    for t in tlistb:
        tid = t.track_id
        if stracks.get(tid, 0):
            del stracks[tid]
    return list(stracks.values())


def remove_duplicate_stracks(stracksa, stracksb):
    pdist = matching.iou_distance(stracksa, stracksb)
    pairs = np.where(pdist < 0.15)
    dupa, dupb = list(), list()
    for p, q in zip(*pairs):
        timep = stracksa[p].frame_id - stracksa[p].start_frame
        timeq = stracksb[q].frame_id - stracksb[q].start_frame
        if timep > timeq:
            dupb.append(q)
        else:
            dupa.append(p)
    resa = [t for i, t in enumerate(stracksa) if not i in dupa]
    resb = [t for i, t in enumerate(stracksb) if not i in dupb]
    return resa, resb
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值