在# import os import pdb import csv import numpy as np… · The Chat Archive
在# import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
# data_path = r"/data2/local_userdata/heyuting/datasets/test/"
# save_path = r"/data2/local_userdata/heyuting/datasets/test/"
# video_files = os.listdir(data_path)
n_clips=16
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = data_path
video_files = os.listdir(data_path)
for videoID in range(len(video_files)):
videoName = video_files[videoID]
print("==>> videoName: ", videoName)
if videoName in ['dvSave-2022_03_21_16_11_40']:
print("==>> pass it: ", videoName)
continue
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.mkdir(save_tensor_Event)
else:
continue
Ratio_of_coincidence= []
for newFileID in tqdm(range(len(fileLIST))):
csv_videoName = fileLIST[newFileID]
# print('---start : ',csv_videoName)
event_tensor_Event = save_tensor_Event +csv_videoName[:-7]+'/'
if os.path.exists(event_tensor_Event):
continue
if not os.path.exists(event_tensor_Event):
os.makedirs(event_tensor_Event)
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
t_gap11 = time_length/n_clips
t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end]
y_clip = y[idx_start:idx_end]
t_clip0 = t[idx_start:idx_end]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(events_index, values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
np.savez_compressed(event_tensor_Event+'{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName)
import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = r"/data2/local_userdata/heyuting/datasets/test/"
video_files = os.listdir(data_path)
n_clips=16
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
for fileID in range(len(video_files)):
videoName = video_files[fileID]
code Copy code
# fileLIST = os.listdir(data_path + videoName + r'/')
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.makedirs(save_tensor_Event)
else:
continue
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
# aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
t_gap11 = time_length/n_clips
t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end]
y_clip = y[idx_start:idx_end]
t_clip0 = t[idx_start:idx_end]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(events_index, values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
# np.savez_compressed(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
np.savez_compressed(os.path.join(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz'))
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName)
中,处理的数据集start_idex和end_idx分别是:1,38,生成的npz15个。为什么是15个?
Show full message · 162 lines Assistant2024-06-05 09:02 UTC Copy response
在您的代码中,处理数据集并生成 npz 文件的主要逻辑在于这部分代码:
python Copy code
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap) < index_t)
idx_2 = torch.where(index_t < (events['timestamp'][0]+(i+1)*t_gap))
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
这里,n_clips 被设置为 16,意味着整个时间序列将被平均划分为 16 个片段。对于每一个时间窗口,代码应该生成一个对应的 npz 文件。然而,您遇到了一个问题,即只生成了 15 个 npz 文件。
生成 npz 文件数目少于预期的可能原因和调试思路如下:
边界条件错误 :在检查 index_t 是否位于每个时间片段的逻辑中,使用 torch.where 找到的 idx_start 和 idx_end 可能在某些边界条件下没有正确处理。特别是 (events['timestamp'][0]+(i+1)*t_gap) 可能恰好大于最后一个时间戳,使得 idx_2 为空数组。因此,在最后一个片段,idx_end 可能未定义(如果 idx_2[0] 为空数组)。
解决这个问题的一个方法是增加对边界的检查:
python Copy code
if len(idx_2[0]) > 0:
idx_end = idx_2[0][-1]
else:
idx_end = len(index_t) - 1 # 使用最后一个索引
循环逻辑的条件处理 :如果最后一个时间片段中没有事件(即所有事件的时间戳都小于最后一个时间分割点),这可能会导致实际生成的 npz 文件数量减少。确保你的数据集在最后一个时间段内有数据。
写入文件时的错误 :在将 tensor tensor_Event_save 保存到 npz 文件时,确保每次循环都正确执行了这个步骤。检查是否有任何错误或异常阻止了某些 npz 文件的保存。
文件系统的延时 :在某些情况下,文件系统的延迟或同步问题也可能导致文件没有立即出现。确保程序完成执行后检查文件数。
通过添加一些打印语句,检查 idx_start 和 idx_end 的值,以及每次循环是否正常执行保存文件的步骔,将有助于进一步调试和定位问题。
Assistant2024-06-05 09:06 UTC Copy response
在您提供的代码中,变量 t_gap_set 设置为 12,它用于定义在处理事件数据时每个时间片段内的 “分辨率” 或时间步总数。这个值涉及到如何将每个时间片段的事件数据时间标准化,将原始事件的时间戳映射到更小的、固定的时间范围(从 0 到 t_gap_set - 1)。
看一下代码中有关 t_clip 的计算部分:
python Copy code
t_clip0 = t[idx_start:idx_end] # 截取当前片段中的时间戳
t_clip = ((t_clip0 - t_clip0[0]) / (t_clip0[-1] - t_clip0[0])) * (t_gap_set - 1.0)
这里,t_clip0 是当前时间窗口内的事件时间戳,t_clip 基于每个时间片段的开始时间(t_clip0[0])和结束时间(t_clip0[-1])进行了重新缩放。时间缩放的目的是将原始时间戳转换为一个 [0, t_gap_set - 1] 范围内的时间索引。
这种转换有两个主要目的:
标准化 :通过标准化时间戳,可以使不同时间片段的事件数据有一个统一的时间尺度,便于进行进一步的分析或模型训练。
离散化 :原始事件数据的时间戳通常是连续的,将时间戳离散化到固定的时间间隔有助于后续操作,如在固定时间格网上构建输入特征。
每个时间段的映射输出是一个范围内的固定数量的时间点(在本例中是12个),这适用于所构建的模型或分析提供数据的一致性和可比性。这提供了一种方式,使得在所有处理的片段中,每个片段尽管可能包含不同数量的事件,但都转换为具有相同长度的时间尺度(此处长度为12)。
当前数据集中,每个序列的start_idex和end_idx都不同,设置n_clips=15是否过于固定?
Assistant2024-06-05 09:07 UTC Copy response
是的,将 n_clips 固定为 15 可能会在处理具有不同时间长度的数据序列时出现问题。这是因为固定分割数 (n_clips) 不一定能适应所有数据序列的时间范围和事件密度,这可能导致以下问题:
时间覆盖不均匀 :对于较长的数据序列,可能每个时间片段包含足够多的事件,但对于较短的数据序列,每个时间片可能包含的事件过少,甚至没有事件。
信息损失 :通过固定时间片数量过度切割较短的数据可以导致信息损失,因为有些小片段可能没有足够的时间分辨率来表示重要的时间特征。
处理效率 :对于事件非常稀疏的序列,划分过多的时间片将导致很多片段为空,这会浪费计算资源并可能影响后续处理效果。
解决策略
为了更灵活地处理具有不同长度的数据序列,您可以考虑以下几种方法:
基于时间长度动态设置片段数 :
计算每个序列的时间长度,然后根据时间长度来确定时间片的数量。例如,可以设定一个每个时间片代表的最大时间长度,然后根据实际序列长度来计算需要多少时间片。
python Copy code
max_duration_per_clip = 1.0 # 设定每个时间片代表的最大秒数
n_clips = int(np.ceil((t[-1] - t[0]) / max_duration_per_clip))
事件驱动的片段划分 :
而非将时间严格平均分割,可以根据事件特征和分布来动态划分时间片。例如,通过查找事件密度突变的时间点来确定片段边界。
基于日期的分层采样 :
如果数据具有周期性特征(例如,一天中的特定时段或一周中的某些天),可以根据这些周期划分时间片。
自定义时间片长度 :
允许用户或基于数据特性来自定义每个时间片的长度,而不是简单地均分总时间。
通过这些方法,可以提高处理数据的灵活性和效率,同时保证不同数据序列均被合理地处理,从而减少信息损失,并更好地适应数据的实际特性。这种灵活性特别重要,尤其是在处理高度异质的数据集时,例如在不同情境下采集的事件相机数据。
在import os
import pdb
import csv
import numpy as np
import cv2
import torch
import pandas as pd
from tqdm import tqdm
import scipy.io
from spconv.pytorch.utils import PointToVoxel
from dv import AedatFile
import numpy as np
import multiprocessing
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def transform_points_to_voxels(data_dict={}, voxel_generator=None, device=torch.device("cuda:0")):
"""
将点云转换为voxel,调用spconv的VoxelGeneratorV2
"""
points = data_dict['points']
# 将points打乱
shuffle_idx = np.random.permutation(points.shape[0])
points = points[shuffle_idx]
data_dict['points'] = points
code Copy code
# 使用spconv生成voxel输出
points = torch.as_tensor(data_dict['points']).to(device)
voxel_output = voxel_generator(points)
# 假设一份点云数据是N*4,那么经过pillar生成后会得到三份数据
# voxels代表了每个生成的voxel数据,维度是[M, 5, 4]
# coordinates代表了每个生成的voxel所在的zyx轴坐标,维度是[M,3]
# num_points代表了每个生成的voxel中有多少个有效的点维度是[m,],因为不满5会被0填充
voxels, coordinates, num_points = voxel_output
voxels = voxels.to(device)
coordinates = coordinates.to(device)
num_points = num_points.to(device)
# 选event数量在前5000的voxel 8000 from(4k+,6k+)
# print(torch.where(num_points>=16)[0].shape)
if num_points.shape[0] < save_voxel:
features = voxels[:, :, 3]
coor = coordinates[:, :]
else:
_, voxels_idx = torch.topk(num_points, save_voxel)
# 将每个voxel的1024个p拼接作为voxel初始特征 16
features = voxels[voxels_idx][:, :, 3]
# 前5000个voxel的三维坐标
coor = coordinates[voxels_idx]
# 将y.x.t改为t,x,y
coor[:, [0, 1, 2]] = coor[:, [2, 1, 0]]
return coor, features
if name == 'main ':
save_voxel = 5000
use_mode = 'frame_exposure_time'
device = torch.device("cuda:0")
# data_path = r"/home/ioe/xxxxx/EventTracking/COESOT/train"
data_path = r"/data2/local_userdata/heyuting/datasets/COESOT/test"
save_path = r"/data2/local_userdata/heyuting/datasets/COESOT/test"
# save_path = r"/home/ioe/xxxxx/COESOT/train"
video_files = os.listdir(data_path)
dvs_img_interval = 1
voxel_generator = PointToVoxel(
# 给定每个voxel的长宽高 [0.05, 0.05, 0.1]
vsize_xyz=[50, 10, 10], # [0.2, 0.25, 0.16] # [50, 10, 10] [50, 35, 26] 因此坐标范围(20,20,20) (20, 34/35, 26)
# 给定点云的范围 [ 0. -40. -3. 70.4 40. 1. ]
coors_range_xyz=[0, 0, 0, 1000, 345, 259],
# 给定每个点云的特征维度,这里是x,y,z,r 其中r是激光雷达反射强度 # 346x260 t,x,y
num_point_features=4,
# 最多选取多少个voxel,训练16000,推理40000
max_num_voxels=16000, # 16000
# 给定每个pillar中有采样多少个点,不够则补0 因此我将neg voxel改为-1;
max_num_points_per_voxel=16, # 1024
device=device
)
Show full message · 173 lines Assistant2024-06-05 09:09 UTC Copy response
在您的代码中,处理每个视频序列的长度或时间段是基于每个视频序列中事件数据的时间戳来确定的。通过以下几个关键步骤,您的代码确定了不同序列(视频片段)的长度:
1. 读取AEDAT格式文件
首先,代码通过读取每个视频文件夹中的 .aedat4 文件收集事件数据。每个文件代表一个视频序列或一段事件记录,其中包含了一系列的事件数据,每个事件数据都有其相应的时间戳、x坐标、y坐标以及极性(polarity):
python Copy code
with AedatFile(read_path) as f:
events = np.hstack([packet for packet in f['events'].numpy()])
2. 提取时间戳和事件的其他属性
在读取整个视频的事件数据后,将这些事件属性转换到 torch 的张量中,并处理这些属性以准备后续的操作:
python Copy code
t_all = torch.tensor(events['timestamp']).unsqueeze(1).to(device)
x_all = torch.tensor(events['x']).unsqueeze(1).to(device)
y_all = torch.tensor(events['y']).unsqueeze(1).to(device)
p_all = torch.tensor(events['polarity']).unsqueeze(1).to(device)
3. 计算事件子集的时间跨度(序列长度)
根据每个视频帧的开始和结束时间,从事件流中提取相应范围的事件。这里的 frame_timestamp 数组包含了视频帧的时间信息(开始和结束时间戳),根据这些时间戳确定每个序列的时间跨度:
python Copy code
for frame_no in range(0, int(frame_num / dvs_img_interval) - 1):
start_idx = np.where(events['timestamp'] >= frame_timestamp[frame_no][0])[0][0]
end_idx = np.where(events['timestamp'] >= frame_timestamp[frame_no][1])[0][0]
t = t_all[start_idx:end_idx]
...
使用 frame_timestamp[frame_no][0] 和 frame_timestamp[frame_no][1] 作为每个事件序列的开始和结束时间戳来确定时间跨度。
4. 时间戳归一化
时间戳的归一化是将每个事件序列中的时间戳缩放到从 0 到 1000 的范围内。归一化是基于每个序列的最小时间戳和时间长度进行的:
python Copy code
time_length = t[-1] - t[0]
t = ((t-t[0]).float() / time_ideth) * 1000
通过这种方式,代码能确保不同长度的序列在处理过程中具有统一的时间尺度。这对于数据处理和后续的学习模型尤其重要,因为它为模型提供了一致性和可比性。
那么参考上段代码,修改# import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
# data_path = r"/data2/local_userdata/heyuting/datasets/test/"
# save_path = r"/data2/local_userdata/heyuting/datasets/test/"
# video_files = os.listdir(data_path)
n_clips=16
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = data_path
video_files = os.listdir(data_path)
for videoID in range(len(video_files)):
videoName = video_files[videoID]
print("==>> videoName: ", videoName)
if videoName in ['dvSave-2022_03_21_16_11_40']:
print("==>> pass it: ", videoName)
continue
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.mkdir(save_tensor_Event)
else:
continue
Ratio_of_coincidence= []
for newFileID in tqdm(range(len(fileLIST))):
csv_videoName = fileLIST[newFileID]
# print('---start : ',csv_videoName)
event_tensor_Event = save_tensor_Event +csv_videoName[:-7]+'/'
if os.path.exists(event_tensor_Event):
continue
if not os.path.exists(event_tensor_Event):
os.makedirs(event_tensor_Event)
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
t_gap11 = time_length/n_clips
t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
Show full message · 159 lines Assistant2024-06-05 09:11 UTC Copy response
为了使生成的每个视频序列的长度或时间段是基于每个视频序列中事件数据的时间戳确定的,我们可以修改代码来提取事件的时间戳信息,并按照时间戳动态决定每个视频段的长度。这样能够产生更准确和有效的数据处理结果。
下面是修改 n_clips 的策略,使其动态调整以适应各个数据文件的事件时间长度:
python Copy code
import os
import numpy as np
import torch
from tqdm import tqdm
from dv import AedatFile
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = r"/data2/local_userdata/heyuting/datasets/test/"
video_files = os.listdir(data_path)
t_gap_set = 12
if __name__ == '__main__':
device = torch.device("cuda:0")
for fileID in range(len(video_files)):
videoName = video_files[fileID]
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.makedirs(save_tensor_Event)
else:
continue
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
with AedatFile(read_path) as f:
events = np.hstack([packet for packet in f['events'].numpy()])
t = events['timestamp']
time_length = t[-1] - t[0]
index_t = torch.tensor(t)
# 设定n_clips为基于事件的时间长度动态调整
min_duration_per_clip = 1000000 # 设定每个时间片段至少包含该时间长度(如1,000,000微秒)
n_clips = max(1, time_length // min_duration_per_clip)
t_gap = int(time_length / n_clips)
for i in range(n_clips):
idx_1 = torch.where((t[0] + i * t_gap) < index_t)[0]
idx_2 = torch.where(index_t < (t[0] + (i + 1) * t_gap))[0]
if len(idx_2) == 0:
idx_end = idx_1[-1]
else:
idx_start = idx_1[0]
idx_end = idx_2[-1]
x_clip = events['x'][idx_start:idx_end + 1]
y_clip = events['y'][idx_start:idx_end + 1]
t_clip0 = index_t[idx_start:idx_end + 1]
t_clip = ((t_clip0 - t_clip0[0]) / (t_clip0[-1] - t_clip0[0]) * (t_gap_set - 1.0)).long()
events_index = torch.stack((x_clip, y_clip, t_clip))
tensor_Event = torch.zeros(346, 260, t_gap_set, device=device)
tensor_Event.index_put_(tuple(events_index), torch.tensor(1., device=device))
np.savez_compressed(os.path.join(save_tensor_Event, 'frame{:04d}.format(i).npz'), tensor_Event=tensor_Event.numpy())
print('---end : ', videoName)
import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
# data_path = r"/data2/local_userdata/heyuting/datasets/test/"
# save_path = r"/data2/local_userdata/heyuting/datasets/test/"
# video_files = os.listdir(data_path)
n_clips=16
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = data_path
video_files = os.listdir(data_path)
for videoID in range(len(video_files)):
videoName = video_files[videoID]
print("==>> videoName: ", videoName)
if videoName in ['dvSave-2022_03_21_16_11_40']:
print("==>> pass it: ", videoName)
continue
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.mkdir(save_tensor_Event)
else:
continue
Ratio_of_coincidence= []
for newFileID in tqdm(range(len(fileLIST))):
csv_videoName = fileLIST[newFileID]
# print('---start : ',csv_videoName)
event_tensor_Event = save_tensor_Event +csv_videoName[:-7]+'/'
if os.path.exists(event_tensor_Event):
continue
if not os.path.exists(event_tensor_Event):
os.makedirs(event_tensor_Event)
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
t_gap11 = time_length/n_clips
t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
Show full message · 172 lines Assistant2024-06-05 09:20 UTC Copy response
在您的代码中,min_duration_per_clip 是设置为 1000000 微秒(即 1 秒)。这个参数的设定是为了确定将视频事件数据划分为多少时间片 (n_clips)。将这个值设置为 1 秒是一种常见的做法,旨在确保每个片段包含至少 1 秒钟的事件数据。
原因及其重要性
时间分辨率和处理 : 设定这样一个时间长度可以确保每个时间片内有足够的事件数据,使得对每个时间片的分析和处理具有统计意义。如果时间片划分得太短,可能会导致某些片段事件数据稀疏,不足以进行有效分析或训练数据模型。
数据的一致性 : 保持时间片长度的一致性有助于比较和评估不同视频或不同时间片段的相似性和差异性。
性能优化 : 防止处理大量非常短的时间片,可能会增加计算的负担,而并不增加太多的信息。较长的时间片可以平衡计算效率和信息量。
实际应用 : 在很多实际应用场景(如监控视频分析、自动驾驶车辆的感知系统等)中,1秒钟的事件流常常包含足够的动态信息来支撑决策。
调整 min_duration_per_clip 的原则
数据集特性 : 根据您处理的数据集的特点(如事件的密度、总时间跨度等)来调整这个值。对于事件密集的数据集,可能需要降低这个数值以获得更细致的时间解析。
目标任务要求 : 考虑您的具体任务(如对象跟踪、行为识别等)可能对时间解析度有不同的要求。
在您的代码中,若一秒作为时间片太长或太短,则可以依据实验结果或数据集的特性来适当调整。能够灵活调整这一参数,将有助于优化处理性能和结果的精度。
现在生成的是# import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
# data_path = r"/data2/local_userdata/heyuting/datasets/test/"
# save_path = r"/data2/local_userdata/heyuting/datasets/test/"
# video_files = os.listdir(data_path)
n_clips=16
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = data_path
video_files = os.listdir(data_path)
for videoID in range(len(video_files)):
videoName = video_files[videoID]
print("==>> videoName: ", videoName)
if videoName in ['dvSave-2022_03_21_16_11_40']:
print("==>> pass it: ", videoName)
continue
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.mkdir(save_tensor_Event)
else:
continue
Ratio_of_coincidence= []
for newFileID in tqdm(range(len(fileLIST))):
csv_videoName = fileLIST[newFileID]
# print('---start : ',csv_videoName)
event_tensor_Event = save_tensor_Event +csv_videoName[:-7]+'/'
if os.path.exists(event_tensor_Event):
continue
if not os.path.exists(event_tensor_Event):
os.makedirs(event_tensor_Event)
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
t_gap11 = time_length/n_clips
t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
Show full message · 169 lines Assistant2024-06-05 09:24 UTC Copy response
您遇到的问题是一些视频序列中生成的 npz 文件数量少于期望的 n_clips。这种情况通常是由边界条件和处理逻辑不匹配造成的。我们来详细探讨可能的原因以及解决策略。
问题分析
时间计算精度 :
在将整个事件时间序列划分为时间片段时,最后一个时间片可能会因为不完全的时间段割或在计算 idx_end 时由于索引范围问题导致被舍弃。
索引边界处理 :
当 torch.where 检索最后一个片段的结束索引时可能返回空数组,这是因为 index_t < (t[0] + (i + 1) * t_gap) 可能不包含任何元素,导致不生成对应的文件。
时间片数量调整 :
因为总事件时间被固定为某个整数的倍数,最后的几个事件可能不足以构成一个完整的时间片。
解决策略
确保包含最后一个时间片 :对于最后一个时间片,你应确保即使它短于 t_gap,也要包括进来。
调整边界条件 : 修改索引的获取方式,确保包含所有的事件,特别是最后一组。
修改后的代码
我将对您的代码进行一些修改,确保最后一个时间片被正确处理,并确保在结束索引为空时能够正确处理。
Copy first response
Not yet included in a published release.
code Copy code
for videoID in range(len(video_files)):
foldName = video_files[videoID]
print("==>> foldName: ", foldName)
# if foldName in ['dvSave-2022_01_26_20_01_46', 'dvSave-2022_03_21_11_09_50',
# 'dvSave-2022_03_21_16_11_40', 'dvSave-2022_03_21_11_12_27',
# 'dvSave-2022_03_21_11_19_37', 'dvSave-2022_02_25_13_21_41',
# 'dvSave-2022_02_25_13_31_18', 'dvSave-2022_03_21_09_05_49']:
# print("==>> pass it: ", foldName)
# continue
if foldName not in ['dvSave-2022_03_21_11_19_37', 'dvSave-2022_03_21_11_12_27']:
print("==>> pass it: ", foldName)
continue
# if 'dvSave-2022_03_21' not in foldName:
# continue
fileLIST = os.listdir(os.path.join(data_path, foldName))
if not os.path.exists(os.path.join(save_path, foldName, foldName+'_voxel')):
os.mkdir(os.path.join(save_path, foldName, foldName+'_voxel'))
else:
continue
mat_save = os.path.join(save_path, foldName, foldName+'_voxel/')
# for FileID in tqdm(range(len(fileLIST))):
# videoName = fileLIST[FileID]
# (filename, extension) = os.path.splitext(videoName)
# if (extension == '.aedat4') : # and ('dvSave-2022_03_21' in foldName):
# # if os.path.exists(mat_save + '{}.mat'.format(filename)):
# # print("==>> Skip this video ... ")
# # continue
aedat4_file = foldName + '.aedat4'
# print('filename:', aedat4_file)
read_path = os.path.join(data_path, foldName, aedat4_file)
# read aeda4;
frame_all = []
frame_exposure_time = []
frame_interval_time = []
with AedatFile(read_path) as f:
# print(f.names)
for frame in f['frames']:
frame_all.append(frame.image)
frame_exposure_time.append([frame.timestamp_start_of_exposure,
frame.timestamp_end_of_exposure]) ## [1607928583397102, 1607928583401102]
frame_interval_time.append([frame.timestamp_start_of_frame,
frame.timestamp_end_of_frame]) ## [1607928583387944, 1607928583410285]
if use_mode == 'frame_exposure_time':
frame_timestamp = frame_exposure_time
elif use_mode == 'frame_interval_time':
frame_timestamp = frame_interval_time
frame_num = len(frame_timestamp)
events = np.hstack([packet for packet in f['events'].numpy()])
t_all = torch.tensor(events['timestamp']).unsqueeze(1).to(device)
x_all = torch.tensor(events['x']).unsqueeze(1).to(device)
y_all = torch.tensor(events['y']).unsqueeze(1).to(device)
p_all = torch.tensor(events['polarity']).unsqueeze(1).to(device)
for frame_no in range(0, int(frame_num / dvs_img_interval) - 1):
start_idx = np.where(events['timestamp'] >= frame_timestamp[frame_no][0])[0][0]
end_idx = np.where(events['timestamp'] >= frame_timestamp[frame_no][1])[0][0]
sub_event = events[start_idx:end_idx]
idx_length = end_idx - start_idx
t = t_all[start_idx: end_idx]
if start_idx == end_idx:
time_length = 0
t = ((t-t).float() / time_length) * 1000
scipy.io.savemat(mat_save + 'frame{:0>4d}.mat'.format(frame_no), mdict={'coor': np.zeros([100, 3]),
'features': np.zeros([100, 16])}) # coor: numpy.nan; features: numpy.nan
print('empty event frame ', frame_no)
continue
else:
time_length = t[-1] - t[0]
# rescale the timestampes to start from 0 up to 1000
t = ((t-t[0]).float() / time_length) * 1000
all_idx = np.where(sub_event['polarity'] != -1) # all event
neg_idx = np.where(sub_event['polarity'] == 0) # neg event
t = t[all_idx]
x = x_all[all_idx]
y = y_all[all_idx]
p = p_all[all_idx]
p[neg_idx] = -1 # negtive voxel change from 0 to -1. because after append 0 operation.
current_events = torch.cat((t, x, y, p), dim=1)
# if current_events.shape[0] < 10: # remove it
# continue
data_dict = {'points': current_events}
coor, features = transform_points_to_voxels(data_dict=data_dict, voxel_generator=voxel_generator,
device=device)
# pdb.set_trace()
coor = coor.cpu().numpy()
features = features.cpu().numpy()
# print('coor', coor)
scipy.io.savemat(mat_save + 'frame{:0>4d}.mat'.format(frame_no), mdict={'coor': coor, 'features': features}) # coor: Nx(t,x,y); features:Nx32 or Nx10024 中,是如何确定不同序列的长度的?
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end]
y_clip = y[idx_start:idx_end]
t_clip0 = t[idx_start:idx_end]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(events_index, values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
np.savez_compressed(event_tensor_Event+'{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName) import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = r"/data2/local_userdata/heyuting/datasets/test/"
video_files = os.listdir(data_path)
n_clips=20
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
for fileID in range(len(video_files)):
videoName = video_files[fileID]
code Copy code
# fileLIST = os.listdir(data_path + videoName + r'/')
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.makedirs(save_tensor_Event)
else:
continue
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
# aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
t_gap11 = time_length/n_clips
t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
for i in range(n_clips):
idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end]
y_clip = y[idx_start:idx_end]
t_clip0 = t[idx_start:idx_end]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(events_index, values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
# np.savez_compressed(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
np.savez_compressed(os.path.join(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz'))
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName)
,使得生成的每个视频序列的长度或时间段是基于每个视频序列中事件数据的时间戳来确定。
n_clips 现在是基于每个视频文件里事件的总时间长度动态计算的,每个时间片段的长度由 min_duration_per_clip 决定。
确保事件的时间索引 (idx_1 和 idx_2) 被正确处理,特别是在处理时间边界时。
使用 index_put_ 方法将事件在 voxel grid 上的映射存储到一个 tensor 中。
通过这种修改,每个视频段的处理将更加灵活和数据驱动,从而更好地适应数据的时间特性。这样的动态调整有助于减少信息遗漏并提高数据处理的准确性。
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end]
y_clip = y[idx_start:idx_end]
t_clip0 = t[idx_start:idx_end]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(events_index, values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
np.savez_compressed(event_tensor_Event+'{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName) import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = r"/data2/local_userdata/heyuting/datasets/test/"
video_files = os.listdir(data_path)
n_clips=20
t_gap_set = 12
if name == 'main ':
device = torch.device("cuda:0")
for fileID in range(len(video_files)):
videoName = video_files[fileID]
code Copy code
# fileLIST = os.listdir(data_path + videoName + r'/')
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.makedirs(save_tensor_Event)
else:
continue
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
# aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
# t_gap11 = time_length/n_clips
# t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
min_duration_per_clip = 1000000
n_clips = max(1, time_length // min_duration_per_clip)
t_gap = int(time_length / n_clips)
for i in range(n_clips):
# idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
# idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
idx_1 = torch.where((t[0] + i * t_gap) < index_t)[0]
idx_2 = torch.where(index_t < (t[0] + (i + 1) * t_gap))[0]
if len(idx_2) == 0:
idx_end = idx_1[-1]
else:
idx_start = idx_1[0]
idx_end = idx_2[-1]
# idx_start= idx_1[0][0]
# idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end+1]
y_clip = y[idx_start:idx_end+1]
t_clip0 = t[idx_start:idx_end+1]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0]) * (t_gap_set-1.0)).long()
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(tuple(events_index), values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
# np.savez_compressed(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
np.savez_compressed(os.path.join(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz'),tensor_Event=tensor_Event.numpy())
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName)
中min_duration_per_clip = 1000000为什么这样设置?
idx_start= idx_1[0][0]
idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end]
y_clip = y[idx_start:idx_end]
t_clip0 = t[idx_start:idx_end]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(events_index, values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
np.savez_compressed(event_tensor_Event+'{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName) import os
import pdb
import csv
import numpy as np
import torch
from tqdm import tqdm
import pdb
from dv import AedatFile
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = r"/data2/local_userdata/heyuting/datasets/test/"
video_files = os.listdir(data_path)
n_clips=20 if name == 'main ':
device = torch.device("cuda:0")
for fileID in range(len(video_files)):
videoName = video_files[fileID]
code Copy code
# fileLIST = os.listdir(data_path + videoName + r'/')
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.makedirs(save_tensor_Event)
else:
continue
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
# aedat_file_path = data_path + videoName + r'/' + csv_videoName
with AedatFile(read_path) as f:
# print(f.names)
events = np.hstack([packet for packet in f['events'].numpy()])
# print(events)
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
time_length = t[-1]-t[0]
# t_gap11 = time_length/n_clips
# t_gap = int((events['timestamp'][-1]-events['timestamp'][0])/n_clips)
index_t = torch.tensor(t)
min_duration_per_clip = 1000000
n_clips = max(1, time_length // min_duration_per_clip)
t_gap = int(time_length / n_clips)
for i in range(n_clips):
# idx_1 = torch.where((events['timestamp'][0]+i*t_gap)<index_t)
# idx_2 = torch.where(index_t<(events['timestamp'][0]+(i+1)*t_gap))
idx_1 = torch.where((t[0] + i * t_gap) < index_t)[0]
idx_2 = torch.where(index_t < (t[0] + (i + 1) * t_gap))[0]
if len(idx_2) == 0:
idx_end = idx_1[-1]
else:
idx_start = idx_1[0]
idx_end = idx_2[-1]
# idx_start= idx_1[0][0]
# idx_end= idx_2[0][-1]
x_clip = x[idx_start:idx_end+1]
y_clip = y[idx_start:idx_end+1]
t_clip0 = t[idx_start:idx_end+1]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
# x = x.astype(np.float)
# y = y.astype(np.float)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
events_index = tuple(events_index)
tensor_Event = torch.zeros(346,260,t_gap_set)
tensor_Event_save=tensor_Event.index_put(tuple(events_index), values = torch.tensor(1.))
# coincidence=((len(x_clip)-tensor_Event_save.sum())/len(x_clip)).tolist()
# Ratio_of_coincidence.append(coincidence)
# if coincidence>0.4:
# print('singal_coincidence: {:.2%}'.format(coincidence))
# np.savez_compressed(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz',tensor_Event = tensor_Event_save)
np.savez_compressed(os.path.join(save_tensor_Event, 'frame{:04d}'.format(i)+'.npz'),tensor_Event=tensor_Event.numpy())
# print('Ratio_of_coincidence——mean: {:.2%}'.format(np.array(Ratio_of_coincidence).mean()))
# print('Ratio_of_coincidence——max: {:.2%}'.format(np.array(Ratio_of_coincidence).max()))
# print('---end : ',csv_videoName)
print('---end : ',videoName)
import os
import numpy as np
import torch
from tqdm import tqdm
from dv import AedatFile
data_path = r"/data2/local_userdata/heyuting/datasets/test/"
save_path = data_path
video_files = os.listdir(data_path)
t_gap_set = 12
if __name__ == '__main__':
device = torch.device("cuda:0")
for fileID in range(len(video_files)):
videoName = video_files[fileID]
print("==>> videoName: ", videoName)
fileLIST = os.listdir(os.path.join(data_path, videoName))
save_tensor_Event = os.path.join(save_path, videoName, videoName + '_tensor')
if not os.path.exists(save_tensor_Event):
os.makedirs(save_tensor_Event)
else:
continue
aedat4_file = videoName + '.aedat4'
read_path = os.path.join(data_path, videoName, aedat4_file)
with AedatFile(read_path) as f:
events = np.hstack([packet for packet in f['events'].numpy()])
t = events['timestamp']
time_length = t[-1]-t[0]
min_duration_per_clip = 1000000
n_clips = max(1, time_length // min_duration_per_clip)
t_gap = int(time_length / n_clips) if n_clips > 1 else time_length
for i in range(n_clips):
start_time = t[0] + i * t_gap
end_time = t[0] + (i + 1) * t_gap if i < n_clips - 1 else t[-1] + 1
idx_1 = (t >= start_time).nonzero()[0]
idx_2 = (t < end_time).nonzero()[0]
idx_start, idx_end = idx_1[0], idx_2[-1]
x_clip = events['x'][idx_start:idx_end + 1]
y_clip = events['y'][idx_start:idx_end + 1]
t_clip0 = t[idx_start:idx_end + 1]
t_clip = ((t_clip0-t_clip0[0]) / (t_clip0[-1]-t_clip0[0])) * (t_gap_set-1.0)
events_index = torch.LongTensor(np.vstack((x_clip,y_clip,t_clip)))
tensor_Event = torch.zeros(346,260,t_gap_set, dtype=torch.float32, device=device)
tensor_Event_save = tensor_Event.index_put(tuple(map(tuple, events_index)), torch.tensor(1.))
np.savez_compressed(os.path.join(save_tensor_Event, 'frame{:04d}.format(i).npz'), tensor_Event=tensor_Event_save.cpu().numpy())
print('---end : ', videoName)
这个修改版注意力放在确保所有的事件都被正确划分到时间片中,特别是包括那些位于边缘但依然重要的事件。