参考:import os import pdb import csv import numpy as np… · The Chat Archive
Explore / Programming 参考:import os import pdb import csv import numpy as np import cv2 import torch import… Save Share Download ▾ Report参考: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 · 331 lines Assistant2024-06-05 09:27 UTC Copy response
Assistant2024-06-05 09:28 UTC Copy response
提供的代码与处理DVS(动态视觉传感器)数据集有关,目的是从这些事件中提取事件信息,将事件转化为体素,并保存张量以供后续使用(可能用于机器学习训练过程)。具体涵盖了以下几个关键方面:
读取DVS数据 :使用 AedatFile 类从路径读取 .aedat4 文件,并提取其中的帧和事件信息。这些数据包括由传感器捕获的事件的 x-y 坐标、时间戳和极性。
点云到体素的转换 :利用 voxel_generator 将点云数据(本例中的事件)转换为体素。体素是三维空间中规则网格上的值,可以用3D卷积神经网络处理。
时间分割 :基于时间戳将所有事件分成时间片段或剪辑,这对处理时间序列数据非常重要,因为事件之间的时间关系极为重要。
张量形成和保存 :将事件数据转换为稀疏张量格式,其中每个非零条目可能代表发生的事件。然后将此张量以压缩的 .npz 格式保存,以实现高效的 I/O 操作。
让我们总结一下系统的预期:
目录设置 :从给定目录读取视频数据,处理它,然后保存到对应的目录结构中。
DVS数据转换 :将每个视频的 .aedat4 文件中的事件数据转换为时间段划分的张量。
效率 :处理应优化为pytorch设备(在这种情况下为GPU),以实现快速操作。
改进和观察:
参数化设置 :核心设置如片段数、时间分辨率和文件路径等应更好地作为配置参数或命令行参数组织,这将使代码更具可重用性和可维护性。
错误和异常处理 :代码缺乏健士的错误处理,这在处理文件 I/O 操作及确保张量操作因时间同步或数据丢失而不出问题时尤其必要。
验证 :缺乏数据验证(例如,确保时间戳在帧和事件之间正确同步)。没有这样的检查,可能存在数据错位问题,进而影响模型训练的准确性。
日志记录 :与其使用打印语句,不如使用更健全的日志记录框架来帮助跟踪过程、调试问题和优化性能。
Assistant2024-06-05 09:30 UTC Copy response
为了确保生成的tensor数量与mat文件的数量一致,您需要确保两者在时间片分割和事件处理方面保持一致。在您的代码中,需要进行以下几个步骤的调整:
核对事件时间戳处理 :确保在处理DVS数据时,每帧的分割精度与处理成mat文件时使用的方法相同。检查和核对t_gap和t_gap_set的计算方法,以及如何从时间戳中切割事件。
同步帧的处理 :在生成mat和tensor文件时,确保时间框架的同步,尤其是每帧的起始和结束时间的计算。
调整事件选取策略 :在生成tensor时,确保根据DVS数据的特性调整事件的选取,包括排除噪声和无关事件。
调试和验证 :增加日志记录和断点调试,以便跟踪每步的处理结果,确保每个步骤的输出符合预期。
优化代码结构 :将配置参数(如帧数、时间间隔等)集中管理,并在代码中增加注释,提高代码的可读性和可维护性。
具体调整建议如下:
细化时间戳处理 :调整t_gap的计算公式,确保它精确对应于生成mat文件时使用的时间间隔。如果源数据帧率固定,可以根据实际帧率和设备性能调整t_gap的值。
调整索引计算 :在计算idx_start和idx_end时,确保这些索引精确切分出所需的事件数据片段。如果有必要,可以根据实际的时间戳范围调整索引的选择范围。
代码审查和测试 :每次修改后,都应该通过单元测试和实际数据测试来验证修改是否有效。并且,可以通过与原始的Mat文件生成过程进行对比测试,确保二者在处理逻辑上一致。
通过逐一审视和调整这些方面,您可以确保在转换过程中生成的tensor数量与mat文件的数量完全一致。同时,建议在实际部署前进行充分的测试,确保所有的调整都能达到预期的效果。
Assistant2024-06-05 09:31 UTC Copy response
为了确保生成的tensor数量与mat文件一臀数量相匹配,重要的是在生成mat文件和tensor文件时,使用相同的事件选取和时间分割策略。下面是一些可以帮助实现这一目标的建议:
1. 确保时间分割策略一致
校验和确保时间分割参数(如n_clips和t_gap)在两种处理(生成mat文件和tensor文件)中完全相同。
确保使用相同的时间戳来分割数据,例如确保frame_timestamp在两种处理中定义和使用方式一致。
2. 同步事件处理逻辑
在处理事件数据之前,要对数据进行预处理,以确保只有有效和相关的事件被选中进行进一步处理。这包括处理事件的极性和过滤噪声。
在转换为voxels前,确保数据的排列、选择逻辑完全匹配。
3. 调整数据保存逻辑
在保存数据之前,添加检查点以验证每步生成的数据量是否与预期匹配。如果发现不匹配,可以通过日志输出进一步调查问题。
确保保存数据到mat文件和numpy压缩文件(npz文件)的代码逻辑完全一致,特别是在数据格式和结构上。
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 4 (8 messages)
Language en
Conversation date Jun 5, 2024
Added to archive Nov 16, 2026
ID 01m7h41qenpbgknt7863g4xmswSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 7a83f640c3bc73372e4a365f0f26f144
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
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,它生成的与RGB相同帧的mat文件数量,现在修改# 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)
,使得生成的tensor数量(npz文件)同RGB一样,注:当前两段代码读取的数据集是一样的,只是处理方式不同。
The code provided is related to working with a DVS (Dynamic Vision Sensor) dataset to extract events, form voxels from these events, and save tensors for further use, probably in machine learning training processes. There are a few key aspects covered:
Reading DVS Data : Utilizing the AedatFile class to read .aedat4 files from a path and extract frame and event information. This data includes x-y coordinates, timestamps, and polarity of the events captured by the sensor.
Transformation of Point Cloud to Voxels : Using a voxel_generator to convert point cloud data (events in this case) into voxels. A voxel is a value on a regular grid in three-dimensional space, which can be processed by 3D convolutional neural networks.
Temporal Slicing : Dividing the complete set of events into slices based on the timestamp to form temporal segments or clips. This is crucial for handling time-series data where the temporal relationship between events is significant.
Tensor Formation and Saving : Converting the event data into sparse tensor format where each non-zero entry might represent the occurrence of an event. This tensor is then saved into compressed .npz format for efficient I/O operations.
Let's summarize what is expected from the system:
Directory Setup : Read video data from a given directory, process it, and then save it to an aligned directory structure.
DVS Data Conversion : Each video's .aedat4 file’s event data is converted into tensors segmented across time.
Efficiency : The processing should be pytorch-device optimized (GPU in this case) for fast operations.
Improvements and Observations:
Parameterization of Settings : Core settings like number of clips, temporal resolutions, and file paths could be better organized as configuration parameters or command line arguments. This could make the code more reusable and maintainable.
Error and Exception Handling : The code lacks robust error handling, which would be necessary especially when dealing with file I/O operations and ensuring tensor operations do not run into issues due time synchronization or missing data.
Validation : There is no validation of data (e.g., ensuring that timestamps are correctly synchronized across frames and events). Without such checks, there could be risks of data misalignment impacting the model's training accuracy down the line.
Logging : Instead of using print statements, a more robust logging framework could help in tracking the process, debugging issues, and optimizing performance.
Debugging these issues, properly parameterizing the configuration, ensuring robust logging and error handling, and performing comprehensive validation would make this code more robust for production or research usage.
对这些问题进行调试,正确参数化配置,确保健壮的日志记录和错误处理,并进行全面的验证,将使这段代码更适合于生产或研究用途。
现在就是# 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)
生成的tensor数量和mat数量对应不上,所以需要参考生成mat的数量计算,修改event_to_tensor
Show full message · 160 lines 那么现在修改# 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)
中在时间片分割进行修改,需要同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 · 334 lines
4. 调试和优化
引入更多的日志记录,以帮助追踪数据处理的每个阶段,特别是在数据分割和tensor转换的步骤。
通过单元测试验证每个关键函数的正确性,确保函数在各种条件下的稳定性。
5. 配置管理
将所有关键配置参数集中管理,例如使用配置文件。这可以帮助快速调整参数而无需修改代码,并确保各个部分使用的配置一致。
例如,可以调整生成tensor和mat文件的核心部分,以确保时间分割和事件处理逻辑一致:
python Copy code
# 确保时间窗口分割和事件索引一致
index_t = torch.tensor(t)
for i in range(n_clips):
start_time = events['timestamp'][0] + i * t_gap
end_time = events['timestamp'][0] + (i + 1) * t_gap
idx_1 = torch.where(start_time < index_t)
idx_2 = torch.where(index_t < end_time)
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)
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.0))
# 保存处理后的数据
output_filename = f'frame{i:04d}.mat'
np.savez_compressed(os.path.join(save_tensor_Event, output_filename), tensor_Event=tensor_complete)
# 在整个处理流程中添加相应的日志记录和异常捕获以确保处理的正确性和稳定性
通过上述步骤,您可以确保从原始DVS数据生成的mat文件和tensor文件在数量和质量上保持一致。同时,通过增强代码的可配置性和可维护性,使其更适应未来可能的需求变化。
Copy first response
Not yet included in a published release.
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一致