解读:import math from lib.models.ceutrack import… · The Chat Archive
Explore / Programming 解读:import math from lib.models.ceutrack import buildceutrack from… Save Share Download ▾ Report解读:import math
from lib.models.ceutrack import build_ceutrack
from lib.test.tracker.basetracker import BaseTracker
import torch
import copy
from lib.test.tracker.vis_utils import gen_visualization
from lib.test.utils.hann import hann2d
from lib.train.data.processing_utils import sample_target
for debug
import cv2
import os
import torch.nn.functional as F
from lib.test.tracker.data_utils import Preprocessor
from lib.utils.box_ops import clip_box
from lib.utils.ce_utils import generate_mask_cond
class CEUTrack(BaseTracker):
def init(self, params, dataset_name):
super(CEUTrack, self).init(params)
network = build_ceutrack(params.cfg, training=False)
network.load_state_dict(torch.load(self.params.checkpoint, map_location=‘cpu’)[‘net’], strict=True)
self.cfg = params.cfg
self.network = network.cuda()
self.network.eval()
self.preprocessor = Preprocessor()
self.state = None
self.feat_sz = self.cfg.TEST.SEARCH_SIZE // self.cfg.MODEL.BACKBONE.STRIDE
motion constrain
self.output_window = hann2d(torch.tensor([self.feat_sz, self.feat_sz]).long(), centered=True).cuda()
for debug
self.debug = params.debug
self.use_visdom = params.debug
self.frame_id = 0
if self.debug:
if not self.use_visdom:
self.save_dir = “debug”
if not os.path.exists(self.save_dir):
os.makedirs(self.save_dir)
else:
self.add_hook()
self._init_visdom(None, 1)
for save boxes from all queries
self.save_all_boxes = params.save_all_boxes
self.z_dict1 = {}
def initialize(self, image, event_template, info: dict, idx=0):
forward the template once
z_patch_arr, resize_factor, z_amask_arr, crop_coor = sample_target(image, info[‘init_bbox’],
self.params.template_factor,
output_sz=self.params.template_size)
self.z_patch_arr = z_patch_arr
template = self.preprocessor.process(z_patch_arr, z_amask_arr)
with torch.no_grad():
self.z_dict1 = template
self.box_mask_z = None
if self.cfg.MODEL.BACKBONE.CE_LOC:
template_bbox = self.transform_bbox_to_crop(info[‘init_bbox’], resize_factor,
template.tensors.device).squeeze(1)
self.box_mask_z = generate_mask_cond(self.cfg, 1, template.tensors.device, template_bbox)
event_template = event_template.cuda()
z = copy.deepcopy(event_template[:, 0])
x, y = event_template[:, 1], event_template[:, 2]
event_template[:, 0] = x
event_template[:, 1] = y
event_template[:, 2] = z
x1, x2 = crop_coor[0] / 10, crop_coor[1] / 10
y1, y2 = crop_coor[2] / 10, crop_coor[3] / 10
x_range, y_range = x2-x1, y2-y1
event_template[:, 0] = (event_template[:, 0]+0.5 - x1) / x_range
event_template[:, 1] = (event_template[:, 1]+0.5 - y1) / y_range
event_template[:, 2] = (event_template[:, 2]+0.5) / 19
indices = (event_template[:, 0] >= 0) & (event_template[:, 0] <= 1) & (
event_template[:, 1] >= 0) & (event_template[:, 1] <= 1)
event_template = torch.index_select(event_template, dim=0, index=indices.nonzero().squeeze(1))
Show full message · 214 lines Assistant2024-06-05 02:12 UTC Copy response
这段代码定义了 CEUTrack 类,它继承自 BaseTracker 类并实现了一个跟踪器用于跟踪物体。下面是关于各部分代码的解读:
导入库与模块:
导入了数学、PyTorch、OpenCV等库,以及项目特定的一些模块如build_ceutrack,用于构建网络模型。
类定义:
CEUTrack 是一个跟踪器类,含有初始化、初始化跟踪、跟踪和内部辅助方法等。
初始化 (init)
在这个方法中,首先调用基类初始化,然后加载并配置了神经网络模型。网络被转移到GPU上并设置为评估模式。
配置了预处理器和跟踪状态。
设置了Hanning窗口,用于在跟踪期间处理得分图。
初始化跟踪 (initialize):
这个方法设置了初始追踪模版和第一帧信息。
使用预处理器处理初始模板,并使用无梯度(torch.no_grad())模式准备模板和事件模板数据。
追踪 (track):
每帧调用此方法来更新跟踪对象的位置。
使用预处理器对当前帧进行处理,并将当前帧和模板投喂到神经网络。
网络输出的得分图通过Hanning窗口加权,用于计算预测框。
映射辅助函数:
map_box_back 和 map_box_back_batch 方法用于将预浽的框映射到原图坐标。
调试和可视化:
Assistant2024-06-05 02:16 UTC Copy response
整体的跟踪流程在 CEUTrack 类中主要包括以下几个步骤:
初始化 (init 方法):
加载配置和预训练的网络模型,将模型加载到GPU并设置为评估模式。
初始化和配置相关的参数和辅助工具,如预处理器、Hanning窗口等。
准备调试和可视化工具,如果启用调试模式,设置保存或显示图像的路径。
设置初始追踪状态 (initialize 方法):
处理初始化时的图像和目标信息,提取目标的模板。
使用预处理器处理提取到的模板图像和掩码。
准备事件模板数据,这包括将事件数据映射到适当的范围并进行归一化。
存储初始化位置和其他跟踪状态信息为后续帧处理做准备。
追踪过程 (track 方法):
对每一新帧图像和事件数据执行此方法。
根据当前状态(前一帧的位置信息)提取当前帧的搜索区域和相关信息。
利用预处理器处理搜索区域图像和当前事件数据,以及进行数据的标准化和归一化。
将模板数据和当前搜索数据投喂到网络模型中,进行前向传播,得到预测的结果。
结合Hanning窗处理网络输出的得分图,以定位当前帧的目标位置。
根据输出的尺寸和偏移图计算目标框的准确位置并映射回原图坐标。
更新状态信息,为下一帧提供参考。
调试与输出:
如果配置了调试模式,在每一步都可以保存或展示处理的图像、得分图等信息,方便调试和验证算法的效果。
可以选择保存每一帧的预测结果和定位框,以便后续分析。
结束或暂停:
如果遇到指定的终止条件或手动暂停,跟踪过程可以被中断。
通过上述步骤,CEUTrack 类实现了对视频中目标的连绝鲳嫡捕追踪,并可以逐帧更新目标的位置信息。通过整合图像处理和深度学习技术,此跟踪器能够高效处理实时视频流数据,并在多种场景下进行准确的目标跟踪。
Assistant2024-06-05 02:17 UTC Copy response
以下是 CEUTrack 类中实现物体追踪的流程,简化为连续的步骤,每步之间用箭头 "→" 表示:
加载及配置 → 初始化跟踪状态 → 追踪循环 → 调试与输出 → 结束或暂停
具体每个阶段的作用:
加载及配置 :加载网络模型和配置相关参数,准备GPU和评估模式。
初始化跟踪状态 :设定初始目标位置和特征,处理首帧图像和事件数据。
追踪循环 :对每帧图像和事件数据执行追踪更新,包括图像预处理、数据标准化、前向网络推导、框位置预测等。
调试与输出 :处理调试输出,包拭保存图像、得分图、预测框等,以及进行实时可视化(如果启用)。
结束或暂停 :根据用户指令或达到视频终点自动结束跟踪。
这个流程是连续循环执行的,直到追踪结束。每一帧的处理都为后续帧提供了必要的状态信息,保证了追踪的连贯性和准确性。
Assistant2024-06-05 02:19 UTC Copy response
在跟踪过程中,确定初始位置和目标对象通常遵循以下步骤:
输入初始框 :
用户输入 :跟踪通常从用户或其他系统给定的初始边界框(BoundingBox)开始,这个框标定了视频中第一帧里目标对象的位置。例如,在监控视频中,用户可能会手动选择一个对象作为跟踪目标。
自动检测 :在某些情况下,初始位置可能通过自动目标检测算法(如YOLO、SSD、Faster R-CNN等)确定。这种方法在视频开始时自动识别并定位对象。
采样目标 :
使用 sample_target 方法对初始帧中的目标区域进行采样。这包括提取目标周围的图像区域以及可能的关联掩码或特征。此步骤可能涉及调整尺寸以符合模型的输入需求。
特征提取 :
对采样得到的图像使用模型的前端(如卷积神经网络的特征提取层)进行特征提取。这些特征将用于之后的模板匹配和位置估计。
设置搜索窗口 :
Hanning窗口 :初始化时可能会设置一个Hanning窗口,这是一个权重窗,用于在之后的跟踪过程中对位置的预测得分进行平滑处理,以便增强中心位置的预测权重,减少边缘的影响。
存储初始状态 :
初始帧处理完成后,将提取的特征、初始框位置和其他必要信息(如图片尺寸、缩放因子等)存储为跟踪的起始状态。
通过上述步骤,跟踪算法在得到目标的初步定位和相关特征后,可以在随后的帧中继续追踪目标的移动。每个后续帧都会根据前一帧的预测位置来调整搜索窗口,再次执行特征匹配和位置估计,从而连续地更新目标位置。
Assistant2024-06-05 02:24 UTC Copy response
这段代码实现了一个名为 BaseTracker 的基础跟踪器类,下面是对其主要组成部分的逐个解读:
导入库
time:用于处理与时间相关的函数。
torch:PyTorch库,用于处理张量运算等。
OrderedDict:来自 _collections,保持元素插入顺序的字典类型。
Visdom:用于创建可视化界面的库。
BaseTracker类
基类定义
初始化函数 __init__
初始化时接受 params 参数,保存为类的属性,同时初始化一个 visdom 属性为 None。
方法 predicts_segmentation_mask
返回一个布尔值,表示是否该跟踪器预测分割掩码,默认为 False。
方法 initialize
抽象方法,需要在派生类中实现。用于在给定图片和信息的情况下初始化模型。
方法 track
抽象方法,也需要在派生类中实现。用于在给定图片和(可选)信息的条件下进行跟踪,并更新模型状态。
方法 visdom_draw_tracking
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 5 (10 messages)
Language zh
Conversation date Jun 5, 2024
Added to archive Nov 16, 2026
ID 01m7h41qen539h1610vnb73y99Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 742ceaa4dab6dc73777b5ce4caaffc75
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
event_template = event_template.unsqueeze(0).unsqueeze(0)
if event_template.shape[2] >= 1024:
event_template, _ = torch.topk(event_template, k=1024, dim=2)
pad_len_temp = 0
elif event_template.shape[2] < 1024:
pad_len_temp = 1024 - event_template.shape[2]
event_template = F.pad(event_template.transpose(-1, -2), (0, pad_len_temp), mode=‘constant’, value=0)
self.event_template = event_template
save states self.state = info[‘init_bbox’]
self.frame_id = idx
if self.save_all_boxes:
‘’‘save all predicted boxes’‘’
all_boxes_save = info[‘init_bbox’] * self.cfg.MODEL.NUM_OBJECT_QUERIES
return {“all_boxes”: all_boxes_save}
def track(self, image, event_search, info: dict = None):
H, W, _ = image.shape
self.frame_id += 1
x_patch_arr, resize_factor, x_amask_arr, crop_coor = sample_target(image, self.state, self.params.search_factor,
output_sz=self.params.search_size) # (x1, y1, w, h)
search = self.preprocessor.process(x_patch_arr, x_amask_arr)
event_search = event_search.cuda()
z = copy.deepcopy(event_search[:, 0])
x, y = event_search[:, 1], event_search[:, 2]
event_search[:, 0] = x
event_search[:, 1] = y
event_search[:, 2] = z
x1, x2 = crop_coor[0] / 10, crop_coor[1] / 10
y1, y2 = crop_coor[2] / 10, crop_coor[3] / 10
x_range, y_range = x2-x1, y2-y1
event_search[:, 0] = (event_search[:, 0]+0.5 - x1) / x_range # x voxel center
event_search[:, 1] = (event_search[:, 1]+0.5 - y1) / y_range # y voxel center
event_search[:, 2] = (event_search[:, 2]+0.5) / 19 # z voxel center (times)
indices = (event_search[:, 0] >= 0) & (event_search[:, 0] <= 1) & (
event_search[:, 1] >= 0) & (event_search[:, 1] <= 1)
event_search = torch.index_select(event_search, dim=0, index=indices.nonzero().squeeze(1))
event_search = event_search.unsqueeze(0).unsqueeze(0)
event frame need to keep same length 16,12–>20, 20 if event_search.shape[2] < 4096:
pad_len_search = 4096 - event_search.shape[2]
else:
event_search, _ = torch.topk(event_search, k=4096, dim=2)
pad_len_search = 0
event_search = F.pad(event_search.transpose(-1, -2), (0, pad_len_search), mode=‘constant’, value=0)
with torch.no_grad():
x_dict = search
merge the template and the search
run the transformer out_dict = self.network.forward(
template=self.z_dict1.tensors, search=x_dict.tensors, event_template=self.event_template,
event_search=event_search, ce_template_mask=self.box_mask_z)
add hann windows pred_score_map = out_dict[‘score_map’]
response = self.output_window * pred_score_map
pred_boxes = self.network.box_head.cal_bbox(response, out_dict[‘size_map’], out_dict[‘offset_map’])
pred_boxes = pred_boxes.view(-1, 4)
Baseline: Take the mean of all pred boxes as the final result pred_box = (pred_boxes.mean(
dim=0) * self.params.search_size / resize_factor).tolist() # (cx, cy, w, h) [0,1]
get the final box result self.state = clip_box(self.map_box_back(pred_box, resize_factor), H, W, margin=10)
for debug if self.debug:
if not self.use_visdom:
x1, y1, w, h = self.state
image_BGR = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.rectangle(image_BGR, (int(x1),int(y1)), (int(x1+w),int(y1+h)), color=(0,0,255), thickness=2)
save_path = os.path.join(self.save_dir, “%04d.jpg” % self.frame_id)
cv2.imwrite(save_path, image_BGR)
else:
self.visdom.register((image, info[‘gt_bbox’].tolist(), self.state), ‘Tracking’, 1, ‘Tracking’)
self.visdom.register(torch.from_numpy(x_patch_arr).permute(2, 0, 1), ‘image’, 1, ‘search_region’)
self.visdom.register(torch.from_numpy(self.z_patch_arr).permute(2, 0, 1), ‘image’, 1, ‘template’)
self.visdom.register(pred_score_map.view(self.feat_sz, self.feat_sz), ‘heatmap’, 1, ‘score_map’)
self.visdom.register((pred_score_map * self.output_window).view(self.feat_sz, self.feat_sz), ‘heatmap’, 1, ‘score_map_hann’)
if ‘removed_indexes_s’ in out_dict and out_dict[‘removed_indexes_s’]:
removed_indexes_s = out_dict[‘removed_indexes_s’]
removed_indexes_s = [removed_indexes_s_i.cpu().numpy() for removed_indexes_s_i in removed_indexes_s]
masked_search = gen_visualization(x_patch_arr, removed_indexes_s)
self.visdom.register(torch.from_numpy(masked_search).permute(2, 0, 1), ‘image’, 1, ‘masked_search’)
while self.pause_mode:
if self.step:
self.step = False
break
if self.save_all_boxes:
‘’‘save all predictions’‘’
all_boxes = self.map_box_back_batch(pred_boxes * self.params.search_size / resize_factor, resize_factor)
all_boxes_save = all_boxes.view(-1).tolist() # (4N, )
return {“target_bbox”: self.state,
“all_boxes”: all_boxes_save}
else:
return {“target_bbox”: self.state}
def map_box_back(self, pred_box: list, resize_factor: float):
cx_prev, cy_prev = self.state[0] + 0.5 * self.state[2], self.state[1] + 0.5 * self.state[3]
cx, cy, w, h = pred_box
half_side = 0.5 * self.params.search_size / resize_factor
cx_real = cx + (cx_prev - half_side)
cy_real = cy + (cy_prev - half_side)
return [cx_real - 0.5 * w, cy_real - 0.5 * h, w, h]
def map_box_back_batch(self, pred_box: torch.Tensor, resize_factor: float):
cx_prev, cy_prev = self.state[0] + 0.5 * self.state[2], self.state[1] + 0.5 * self.state[3]
cx, cy, w, h = pred_box.unbind(-1) # (N,4) --> (N,)
half_side = 0.5 * self.params.search_size / resize_factor
cx_real = cx + (cx_prev - half_side)
cy_real = cy + (cy_prev - half_side)
return torch.stack([cx_real - 0.5 * w, cy_real - 0.5 * h, w, h], dim=-1)
def add_hook(self):
conv_features, enc_attn_weights, dec_attn_weights = [], [], []
for i in range(12):
self.network.backbone.blocks[i].attn.register_forward_hook(
lambda self, input, output: enc_attn_weights.append(output[1]) lambda self, input, output: enc_attn_weights.append(output[1])
)
self.enc_attn_weights = enc_attn_weights
def get_tracker_class():
return CEUTrack (中文回答)
如果启用调试模式,将输出图像、搜索区、模板和得分图等。
使用Visdom进行实时可视化。
钩子函数 (add_hook):
可用于在神经网络的特定层添加钩子,这在分析和调试网络行为时非常有用。
整体而言,CEUTrack 类为在视频流中跟踪物体提供了一种基于神经网络的方法,通过处理输入的图像和事件数据,并利用预训练的模型进行特征提取和位置预测。这个类充分利用了现代深度学习技术进行实时物体跟踪。
解读:import time
import torch
from _collections import OrderedDict
from lib.train.data.processing_utils import transform_image_to_crop
from lib.vis.visdom_cus import Visdom
class BaseTracker:
"""Base class for all trackers."""
code Copy code
def __init__(self, params):
self.params = params
self.visdom = None
def predicts_segmentation_mask(self):
return False
def initialize(self, image, info: dict) -> dict:
"""Overload this function in your tracker. This should initialize the model."""
raise NotImplementedError
def track(self, image, info: dict = None) -> dict:
"""Overload this function in your tracker. This should track in the frame and update the model."""
raise NotImplementedError
def visdom_draw_tracking(self, image, box, segmentation=None):
if isinstance(box, OrderedDict):
box = [v for k, v in box.items()]
else:
box = (box,)
if segmentation is None:
self.visdom.register((image, *box), 'Tracking', 1, 'Tracking')
else:
self.visdom.register((image, *box, segmentation), 'Tracking', 1, 'Tracking')
def transform_bbox_to_crop(self, box_in, resize_factor, device, box_extract=None, crop_type='template'):
# box_in: list [x1, y1, w, h], not normalized
# box_extract: same as box_in
# out bbox: Torch.tensor [1, 1, 4], x1y1wh, normalized
if crop_type == 'template':
crop_sz = torch.Tensor([self.params.template_size, self.params.template_size])
elif crop_type == 'search':
crop_sz = torch.Tensor([self.params.search_size, self.params.search_size])
else:
raise NotImplementedError
box_in = torch.tensor(box_in)
if box_extract is None:
box_extract = box_in
else:
box_extract = torch.tensor(box_extract)
template_bbox = transform_image_to_crop(box_in, box_extract, resize_factor, crop_sz, normalize=True)
template_bbox = template_bbox.view(1, 1, 4).to(device)
return template_bbox
def _init_visdom(self, visdom_info, debug):
visdom_info = {} if visdom_info is None else visdom_info
self.pause_mode = False
self.step = False
self.next_seq = False
if debug > 0 and visdom_info.get('use_visdom', True):
try:
self.visdom = Visdom(debug, {'handler': self._visdom_ui_handler, 'win_id': 'Tracking'},
visdom_info=visdom_info)
# # Show help
# help_text = 'You can pause/unpause the tracker by pressing ''space'' with the ''Tracking'' window ' \
# 'selected. During paused mode, you can track for one frame by pressing the right arrow key.' \
# 'To enable/disable plotting of a data block, tick/untick the corresponding entry in ' \
# 'block list.'
# self.visdom.register(help_text, 'text', 1, 'Help')
except:
time.sleep(0.5)
print('!!! WARNING: Visdom could not start, so using matplotlib visualization instead !!!\n'
'!!! Start Visdom in a separate terminal window by typing \'visdom\' !!!')
def _visdom_ui_handler(self, data):
if data['event_type'] == 'KeyPress':
if data['key'] == ' ':
self.pause_mode = not self.pause_mode
elif data['key'] == 'ArrowRight' and self.pause_mode:
self.step = True
elif data['key'] == 'n':
self.next_seq = True
Show full message · 89 lines
如果提供了 segmentation 掩码,则一起绘制图像、边框和分割掩码。
如果只有边框信息,则只绘制图像和边框。
方法 transform_bbox_to_crop
将边框信息变换以适应不同的图像裁剪需求,支持模板和搜索两种类型。
此方法利用 transform_image_to_crop 函数(未展示在代码中)将边框和图像处理到特定的尺寸,并进行归一化。
方法 _init_visdom
初始化 visdom 对象用于实时可视化跟踪结果。
在调试模式下启用,并通过 visdom_info 配置参数。
在尝试并失败启动 visdom 后,会有错误处理逻辑输出警告。
方法 _visdom_ui_handler
为 visdom 界面注册事件处理程序,如键盘事件。
处理空格键(暂停/继续),右箭头(在暂停时单步执行),以及 'n' 键(可能用于跳转到下一序列)。
总结 该代码为实现多种跟踪算法提供了一个共通的框架。不直接执行具体的跟踪逻辑,而是定义了必须由子类实现的接口和基本的可视化工具。这种设计抽象了通用功能,并提供了灵活性以适应不同的跟踪需求和算法特性。
Copy first response
Not yet included in a published release.