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"
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 文件路径
"""
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)
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]
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)
ort_sess = onnxruntime.InferenceSession(args.model_path, providers=['CUDAExecutionProvider'])
folder_path = "/home/hitsz/yk_workspace/Yolov5_track/db_tools/human_feature/deature_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:
start_time = time.time()
cursor.execute("SELECT MAX(id) FROM new_detection_tracking_results_1")
max_id = cursor.fetchone()[0]
result = cursor.fetchone()
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]
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 = feature
gallery_feats = feat
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
class STrack(BaseTrack):
shared_kalman = KalmanFilter()
def __init__(self, tlwh,tlwh_ori, score, cls):
self._tlwh = np.asarray(tlwh, dtype=np.float32)
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()
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.frame_id = frame_id
self.start_frame = frame_id
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
new_tlwh = new_track.tlwh
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.tlwh_to_tcah(new_tlwh))
self._tlwh_ori = new_track._tlwh_ori
self.state = TrackState.Tracked
self.is_activated = True
self.score = new_track.score
@property
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]
ret[0] -= ret[2] / 2
return ret
@property
def tlwh_ori(self):
ret = self._tlwh_ori.copy()
return ret
@property
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
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
@staticmethod
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
def tlbr_to_tlwh(tlbr):
ret = np.asarray(tlbr).copy()
ret[2:] -= ret[:2]
return ret
@staticmethod
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 = []
self.lost_stracks = []
self.removed_stracks = []
self.frame_id = 0
self.track_buffer=track_buffer
self.track_thresh = track_thresh
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()
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
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, _):
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)
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'''
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 = []
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'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
STrack.multi_predict(strack_pool)
dists = matching.iou_distance(strack_pool, detections)
dists = matching.fuse_score(dists, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.match_thresh)
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'''
if len(dets_second) > 0:
'''Detections'''
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)
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)
output_stracks = [track for track in self.tracked_stracks if track.is_activated]
outputs = []
for t in output_stracks:
output= []
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