from utils.event_readers import FixedSizeEventReader, FixedDurationEventReader
from utils.inference_utils import events_to_voxel_grid, events_to_voxel_grid_pytorch
from utils.timers import Timer
import time
from image_reconstructor import ImageReconstructor
from options.inference_options import set_inference_options
from PIL import Image
from dv import AedatFile
def extract_davis(aedat_file_path, dvs_img_interval):
frame_no = 0
frame_all = []
frame_exposure_time = []
frame_interval_time = []
# use_mode = 'frame_exposure_time' #### default mode
use_mode = 'frame_interval_time'
with AedatFile(aedat_file_path) as f:
# list all the names of streams in the file
print(f.names)
# extract timestamps of each frame
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]
code
# pdb.set_trace()
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)
# Access dimensions of the event stream
height, width = f['events'].size # 260 346
event_frame = 255 * np.ones((height, width, 3), dtype=np.uint8)
# loop through the "events" stream
# events = np.hstack([packet for packet in f['events'].numpy()])
# # Access information of all events by type
# timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
# pdb.set_trace()
# save event_img
idx = np.round(np.linspace(0, len(frame_timestamp) - 1, int(frame_num / dvs_img_interval))).astype(
int) ## frame index [0, 1, 2, ... , 3847]
frame_timestamp = np.array(frame_timestamp)[idx] ## (3848, 2)
# another reader # speed up
# events will be a named numpy array
events = np.hstack([packet for packet in f['events'].numpy()])
timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
return timestamps, x, y, polarities, frame_num, frame_timestamp
#######################################################################################################
Main Function
#######################################################################################################
if name == "main":
device = torch.device("cuda:0")
# data_path = r"/home/ioe/xxxxx/EventTracking/COESOT/train"
data_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
save_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
video_files = os.listdir(data_path)
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
code
报错:==>> foldName: dvSave-2021_12_21_11_53_57
['events', 'frames', 'imu', 'triggers']
Device: cuda:0
Loading model pretrained/E2VID_lightweight.pth.tar...
Using TransposedConvLayer (fast, with checkerboard artefacts)
== Image reconstruction ==
Image size: 260x346
== Event preprocessing ==
Will normalize event tensors.
== Image Writer ==
Will not write images to disk.
Traceback (most recent call last):
File "run_reconstruction_COESOT.py", line 220, in
last_timestamp, frame_no, save_img_path)
TypeError: update_reconstruction() takes from 3 to 4 positional arguments but 6 were given
== Timing statistics ==
Events -> Device (voxel grid): 0.23 ms
Voxel grid voting: 4.56 ms
Processing entire dataset: 32.02 ms
Building event tensor: 5.12 ms 说明一下原因,(给出修改建议,中文回答)
这是import torch
import cv2
import numpy as np
from model.model import *
from utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter
from utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction
from utils.util import robust_min, robust_max
from utils.timers import CudaTimer, cuda_timers
from os.path import join
from collections import deque
import torch.nn.functional as F
class ImageReconstructor:
def init(self, model, height, width, num_bins, options):
from utils.event_readers import FixedSizeEventReader, FixedDurationEventReader
from utils.inference_utils import events_to_voxel_grid, events_to_voxel_grid_pytorch
from utils.timers import Timer
import time
from image_reconstructor import ImageReconstructor
from options.inference_options import set_inference_options
from PIL import Image
from dv import AedatFile
def extract_davis(aedat_file_path, dvs_img_interval):
frame_no = 0
frame_all = []
frame_exposure_time = []
frame_interval_time = []
# use_mode = 'frame_exposure_time' #### default mode
use_mode = 'frame_interval_time'
with AedatFile(aedat_file_path) as f:
# list all the names of streams in the file
print(f.names)
# extract timestamps of each frame
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]
code
Assistant
由于您希望图像被写入磁盘,但当前输出信息显示“Will not write images to disk”,这表明 ImageWriter 的设置可能没有启用图像保存功能。我们需要进一步检查和修改 ImageWriter 类或与之相关的配置,确保图像能被写入磁盘。
from utils.event_readers import FixedSizeEventReader, FixedDurationEventReader
from utils.inference_utils import events_to_voxel_grid, events_to_voxel_grid_pytorch
from utils.timers import Timer
import time
from image_reconstructor import ImageReconstructor
from options.inference_options import set_inference_options
from PIL import Image
from dv import AedatFile
def extract_davis(aedat_file_path, dvs_img_interval):
frame_no = 0
frame_all = []
frame_exposure_time = []
frame_interval_time = []
# use_mode = 'frame_exposure_time' #### default mode
use_mode = 'frame_interval_time'
with AedatFile(aedat_file_path) as f:
# list all the names of streams in the file
print(f.names)
# extract timestamps of each frame
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]
code
# pdb.set_trace()
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)
# Access dimensions of the event stream
height, width = f['events'].size # 260 346
event_frame = 255 * np.ones((height, width, 3), dtype=np.uint8)
# loop through the "events" stream
# events = np.hstack([packet for packet in f['events'].numpy()])
# # Access information of all events by type
# timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
# pdb.set_trace()
# save event_img
idx = np.round(np.linspace(0, len(frame_timestamp) - 1, int(frame_num / dvs_img_interval))).astype(
int) ## frame index [0, 1, 2, ... , 3847]
frame_timestamp = np.array(frame_timestamp)[idx] ## (3848, 2)
# another reader # speed up
# events will be a named numpy array
events = np.hstack([packet for packet in f['events'].numpy()])
timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
return timestamps, x, y, polarities, frame_num, frame_timestamp
#######################################################################################################
这是:from .util import robust_min, robust_max
from .path_utils import ensure_dir
from .timers import Timer, CudaTimer
from .loading_utils import get_device
from os.path import join
from math import ceil, floor
from torch.nn import ReflectionPad2d
import numpy as np
import torch
import cv2
from collections import deque
import atexit
import scipy.stats as st
import torch.nn.functional as F
from math import sqrt
def make_event_preview(events, mode='red-blue', num_bins_to_show=-1):
# events: [1 x C x H x W] event tensor
# mode: 'red-blue' or 'grayscale'
# num_bins_to_show: number of bins of the voxel grid to show. -1 means show all bins.
assert(mode in ['red-blue', 'grayscale'])
if num_bins_to_show < 0:
sum_events = torch.sum(events[0, :, :, :], dim=0).detach().cpu().numpy()
else:
sum_events = torch.sum(events[0, -num_bins_to_show:, :, :], dim=0).detach().cpu().numpy()
code
if mode == 'red-blue':
# Red-blue mode
# positive events: blue, negative events: red
event_preview = np.zeros((sum_events.shape[0], sum_events.shape[1], 3), dtype=np.uint8)
b = event_preview[:, :, 0]
r = event_preview[:, :, 2]
b[sum_events > 0] = 255
r[sum_events < 0] = 255
else:
# Grayscale mode
# normalize event image to [0, 255] for display
m, M = -10.0, 10.0
event_preview = np.clip((255.0 * (sum_events - m) / (M - m)).astype(np.uint8), 0, 255)
return event_preview
class EventPreprocessor:
"""
Utility class to preprocess event tensors.
Can perform operations such as hot pixel removing, event tensor normalization,
or flipping the event tensor.
"""
from utils.event_readers import FixedSizeEventReader, FixedDurationEventReader
from utils.inference_utils import events_to_voxel_grid, events_to_voxel_grid_pytorch
from utils.timers import Timer
import time
from image_reconstructor import ImageReconstructor
from options.inference_options import set_inference_options
from PIL import Image
from dv import AedatFile
def extract_davis(aedat_file_path, dvs_img_interval):
frame_no = 0
frame_all = []
frame_exposure_time = []
frame_interval_time = []
# use_mode = 'frame_exposure_time' #### default mode
use_mode = 'frame_interval_time'
with AedatFile(aedat_file_path) as f:
# list all the names of streams in the file
print(f.names)
# extract timestamps of each frame
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]
我们使用:reconstructor.update_reconstruction(event_tensor, start_index + num_events_in_window,
last_timestamp, frame_no, save_img_path) ,那么应该如何修改import torch
import cv2
import numpy as np
from model.model import *
from utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter
from utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction
from utils.util import robust_min, robust_max
from utils.timers import CudaTimer, cuda_timers
from os.path import join
from collections import deque
import torch.nn.functional as F
class ImageReconstructor:
def init(self, model, height, width, num_bins, options):
class ImageWriter:
...
def __call__(self, img, event_tensor_id, stamp, save_path):
if not self.output_folder or not save_path:
return
image_filepath = join(save_path, f'frame_{event_tensor_id}.png')
cv2.imwrite(image_filepath, img)
# 如果有时间戳信息,处理时间戳信息的保存
if stamp is not None:
with open(join(save_path, 'timestamps.txt'), 'a') as f:
f.write(f'{stamp}\n')
这是from .util import robust_min, robust_max
from .path_utils import ensure_dir
from .timers import Timer, CudaTimer
from .loading_utils import get_device
from os.path import join
from math import ceil, floor
from torch.nn import ReflectionPad2d
import numpy as np
import torch
import cv2
from collections import deque
import atexit
import scipy.stats as st
import torch.nn.functional as F
from math import sqrt
def make_event_preview(events, mode='red-blue', num_bins_to_show=-1):
# events: [1 x C x H x W] event tensor
# mode: 'red-blue' or 'grayscale'
# num_bins_to_show: number of bins of the voxel grid to show. -1 means show all bins.
assert(mode in ['red-blue', 'grayscale'])
if num_bins_to_show < 0:
sum_events = torch.sum(events[0, :, :, :], dim=0).detach().cpu().numpy()
else:
sum_events = torch.sum(events[0, -num_bins_to_show:, :, :], dim=0).detach().cpu().numpy()
code
if mode == 'red-blue':
# Red-blue mode
# positive events: blue, negative events: red
event_preview = np.zeros((sum_events.shape[0], sum_events.shape[1], 3), dtype=np.uint8)
b = event_preview[:, :, 0]
r = event_preview[:, :, 2]
b[sum_events > 0] = 255
r[sum_events < 0] = 255
else:
# Grayscale mode
# normalize event image to [0, 255] for display
m, M = -10.0, 10.0
event_preview = np.clip((255.0 * (sum_events - m) / (M - m)).astype(np.uint8), 0, 255)
return event_preview
class EventPreprocessor:
"""
Utility class to preprocess event tensors.
Can perform operations such as hot pixel removing, event tensor normalization,
or flipping the event tensor.
"""
class ImageWriter:
...
def __call__(self, img, event_tensor_id, stamp, save_path):
if not save_path:
print("Save path is not provided. Skipping save.")
return
output_path = join(save_path, f'frame_{event_tensor_id}.png')
cv2.imwrite(output_path, img)
if stamp is not None:
timestamp_path = join(save_path, 'timestamps.txt')
with open(timestamp_path, 'a') as f:
f.write(f'{stamp}\n')
if not os.path.exists(save_img_path):
print(f"Directory {save_img_path} does not exist. Attempting to create.")
os.makedirs(save_img_path, exist_ok=True)
from utils.event_readers import FixedSizeEventReader, FixedDurationEventReader
from utils.inference_utils import events_to_voxel_grid, events_to_voxel_grid_pytorch
from utils.timers import Timer
import time
from image_reconstructor import ImageReconstructor
from options.inference_options import set_inference_options
from PIL import Image
from dv import AedatFile
def extract_davis(aedat_file_path, dvs_img_interval):
frame_no = 0
frame_all = []
frame_exposure_time = []
frame_interval_time = []
# use_mode = 'frame_exposure_time' #### default mode
use_mode = 'frame_interval_time'
with AedatFile(aedat_file_path) as f:
# list all the names of streams in the file
print(f.names)
# extract timestamps of each frame
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]
code
# pdb.set_trace()
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)
# Access dimensions of the event stream
height, width = f['events'].size # 260 346
event_frame = 255 * np.ones((height, width, 3), dtype=np.uint8)
# loop through the "events" stream
# events = np.hstack([packet for packet in f['events'].numpy()])
# # Access information of all events by type
# timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
# pdb.set_trace()
# save event_img
idx = np.round(np.linspace(0, len(frame_timestamp) - 1, int(frame_num / dvs_img_interval))).astype(
int) ## frame index [0, 1, 2, ... , 3847]
frame_timestamp = np.array(frame_timestamp)[idx] ## (3848, 2)
# another reader # speed up
# events will be a named numpy array
events = np.hstack([packet for packet in f['events'].numpy()])
timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
return timestamps, x, y, polarities, frame_num, frame_timestamp
#######################################################################################################
# if foldName not in ['dvSave-2022_02_07_22_19_02']:
# continue
aedat_file_path = os.path.join(data_path, foldName, foldName+'.aedat4')
save_img_path = os.path.join(save_path, foldName, foldName+'_recon')
if not os.path.exists(save_img_path):
os.makedirs(save_img_path)
# dvs_img_interval = 1
# for root, dirs, files in os.walk(aedat_path):
# for file in files:
# (filename, extension) = os.path.splitext(file)
# print("==>> filename: ", filename)
# if (extension == '.aedat4'):
# if filename + '_aps' in os.listdir(root) or filename + '_dvs' in os.listdir(root):
# print("==>> Skip this video ... ")
# continue
# save_path_dvs = os.path.join(root, filename, filename+'_dvs')
# save_path_aps = os.path.join(root, filename, filename+'_aps')
# aedat_file_path = os.path.join(root, filename + '.aedat4')
# filename_txt_path = os.path.join(root, filename+'_timestamp.txt')
# croped_events_path = os.path.join(root, filename+'_events.txt')
# if not os.path.exists(save_path_dvs):
# os.makedirs(save_path_dvs)
# if not os.path.exists(save_path_aps):
# os.makedirs(save_path_aps)
timestamps, x, y, polarities, frame_num, frame_timestamp = extract_davis(aedat_file_path, 1) ## (4391964,)
# all_events = [timestamps, x, y, polarities]
all_events = np.zeros((timestamps.shape[0], 4))
all_events[:, 0] = timestamps
all_events[:, 1] = x
all_events[:, 2] = y
all_events[:, 3] = polarities
# pdb.set_trace()
parser = argparse.ArgumentParser(description='Evaluating a trained network')
parser.add_argument('-c', '--path_to_model', required=True, type=str, help='path to model weights')
parser.add_argument('-i', '--input_file', required=False, type=str)
parser.add_argument('--fixed_duration', dest='fixed_duration', action='store_true')
parser.set_defaults(fixed_duration=False)
parser.add_argument('-N', '--window_size', default=500000, type=int,
help="Size of each event window, in number of events. Ignored if --fixed_duration=True")
parser.add_argument('-T', '--window_duration', default=33.33, type=float,
help="Duration of each event window, in milliseconds. Ignored if --fixed_duration=False")
parser.add_argument('--num_events_per_pixel', default=0.35, type=float,
help='in case N (window size) is not specified, it will be automatically computed as N = width * height * num_events_per_pixel')
parser.add_argument('--skipevents', default=0, type=int)
parser.add_argument('--suboffset', default=0, type=int)
parser.add_argument('--compute_voxel_grid_on_cpu', dest='compute_voxel_grid_on_cpu',
action='store_true')
parser.set_defaults(compute_voxel_grid_on_cpu=False)
set_inference_options(parser)
args = parser.parse_args()
# Load model
device = get_device(args.use_gpu)
model = load_model(args.path_to_model, device)
# model = load_model(args.path_to_model)
model = model.to(device)
model.eval()
# pdb.set_trace()
height, width = 260, 346
reconstructor = ImageReconstructor(model, height, width, model.num_bins, args)
start_s = 0
""" Read chunks of events using Pandas """
for frame_no in range(0, frame_num-1):
# Loop through the events and reconstruct images
N = frame_timestamp[frame_no][1] - frame_timestamp[frame_no][0]
# if not args.fixed_duration:
# if N is None:
# N = int(width * height * args.num_events_per_pixel)
# print(
# 'Will use {} events per tensor (automatically estimated with num_events_per_pixel={:0.2f}).'.format(
# N, args.num_events_per_pixel))
# else:
# print('Will use {} events per tensor (user-specified)'.format(N))
# mean_num_events_per_pixel = float(N) / float(width * height)
# if mean_num_events_per_pixel < 0.1:
# print('!!Warning!! the number of events used ({}) seems to be low compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
# elif mean_num_events_per_pixel > 1.5:
# print('!!Warning!! the number of events used ({}) seems to be high compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
initial_offset = args.skipevents
sub_offset = args.suboffset
start_index = initial_offset + sub_offset
if args.compute_voxel_grid_on_cpu:
print('Will compute voxel grid on CPU.')
with Timer('Processing entire dataset'):
# event_window = all_events[:N, :]
# event_window = all_events[start_s: start_s+N, :]
# last_timestamp = event_window[-1, 0]
# start_s += N
start_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][0])[0][0]
end_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][1])[0][0]
event_window = all_events[start_idx:end_idx]
last_timestamp = event_window[-1, 0]
with Timer('Building event tensor'):
if args.compute_voxel_grid_on_cpu:
# pdb.set_trace()
event_tensor = events_to_voxel_grid(event_window, num_bins=model.num_bins, width=width,
height=height)
event_tensor = torch.from_numpy(event_tensor)
else:
# pdb.set_trace()
event_tensor = events_to_voxel_grid_pytorch(event_window, num_bins=model.num_bins,
width=width, height=height, device=device)
num_events_in_window = event_window.shape[0]
reconstructor.update_reconstruction(event_tensor, start_index + num_events_in_window,
last_timestamp, frame_no, save_img_path)
start_index += num_events_in_window
self.model = model
self.use_gpu = options.use_gpu
self.device = torch.device('cuda:0') if self.use_gpu else torch.device('cpu')
self.height = height
self.width = width
self.num_bins = num_bins
self.initialize(self.height, self.width, options)
def initialize(self, height, width, options):
print('== Image reconstruction == ')
print('Image size: {}x{}'.format(self.height, self.width))
self.no_recurrent = options.no_recurrent
if self.no_recurrent:
print('!!Recurrent connection disabled!!')
self.perform_color_reconstruction = options.color # whether to perform color reconstruction (only use this with the DAVIS346color)
if self.perform_color_reconstruction:
if options.auto_hdr:
print('!!Warning: disabling auto HDR for color reconstruction!!')
options.auto_hdr = False # disable auto_hdr for color reconstruction (otherwise, each channel will be normalized independently)
self.crop = CropParameters(self.width, self.height, self.model.num_encoders)
self.last_states_for_each_channel = {'grayscale': None}
if self.perform_color_reconstruction:
self.crop_halfres = CropParameters(int(width / 2), int(height / 2),
self.model.num_encoders)
for channel in ['R', 'G', 'B', 'W']:
self.last_states_for_each_channel[channel] = None
self.event_preprocessor = EventPreprocessor(options)
self.intensity_rescaler = IntensityRescaler(options)
self.image_filter = ImageFilter(options)
self.unsharp_mask_filter = UnsharpMaskFilter(options, device=self.device)
self.image_writer = ImageWriter(options)
self.image_display = ImageDisplay(options)
def update_reconstruction(self, event_tensor, event_tensor_id, stamp=None):
with torch.no_grad():
with CudaTimer('Reconstruction'):
with CudaTimer('NumPy (CPU) -> Tensor (GPU)'):
events = event_tensor.unsqueeze(dim=0)
events = events.to(self.device)
events = self.event_preprocessor(events)
# Resize tensor to [1 x C x crop_size x crop_size] by applying zero padding
events_for_each_channel = {'grayscale': self.crop.pad(events)}
reconstructions_for_each_channel = {}
if self.perform_color_reconstruction:
events_for_each_channel['R'] = self.crop_halfres.pad(events[:, :, 0::2, 0::2])
events_for_each_channel['G'] = self.crop_halfres.pad(events[:, :, 0::2, 1::2])
events_for_each_channel['W'] = self.crop_halfres.pad(events[:, :, 1::2, 0::2])
events_for_each_channel['B'] = self.crop_halfres.pad(events[:, :, 1::2, 1::2])
# Reconstruct new intensity image for each channel (grayscale + RGBW if color reconstruction is enabled)
for channel in events_for_each_channel.keys():
with CudaTimer('Inference'):
new_predicted_frame, states = self.model(events_for_each_channel[channel],
self.last_states_for_each_channel[channel])
if self.no_recurrent:
self.last_states_for_each_channel[channel] = None
else:
self.last_states_for_each_channel[channel] = states
# Output reconstructed image
crop = self.crop if channel == 'grayscale' else self.crop_halfres
# Unsharp mask (on GPU)
new_predicted_frame = self.unsharp_mask_filter(new_predicted_frame)
# Intensity rescaler (on GPU)
new_predicted_frame = self.intensity_rescaler(new_predicted_frame)
with CudaTimer('Tensor (GPU) -> NumPy (CPU)'):
reconstructions_for_each_channel[channel] = new_predicted_frame[0, 0, crop.iy0:crop.iy1,
crop.ix0:crop.ix1].cpu().numpy()
if self.perform_color_reconstruction:
out = merge_channels_into_color_image(reconstructions_for_each_channel)
else:
out = reconstructions_for_each_channel['grayscale']
# Post-processing, e.g bilateral filter (on CPU)
out = self.image_filter(out)
self.image_writer(out, event_tensor_id, stamp, events=events)
self.image_display(out, events)
# pdb.set_trace()
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)
# Access dimensions of the event stream
height, width = f['events'].size # 260 346
event_frame = 255 * np.ones((height, width, 3), dtype=np.uint8)
# loop through the "events" stream
# events = np.hstack([packet for packet in f['events'].numpy()])
# # Access information of all events by type
# timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
# pdb.set_trace()
# save event_img
idx = np.round(np.linspace(0, len(frame_timestamp) - 1, int(frame_num / dvs_img_interval))).astype(
int) ## frame index [0, 1, 2, ... , 3847]
frame_timestamp = np.array(frame_timestamp)[idx] ## (3848, 2)
# another reader # speed up
# events will be a named numpy array
events = np.hstack([packet for packet in f['events'].numpy()])
timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
return timestamps, x, y, polarities, frame_num, frame_timestamp
#######################################################################################################
Main Function
#######################################################################################################
if name == "main":
device = torch.device("cuda:0")
# data_path = r"/home/ioe/xxxxx/EventTracking/COESOT/train"
data_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
save_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
video_files = os.listdir(data_path)
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
code
if foldName not in ['dvSave-2021_12_21_11_53_57']:
continue
aedat_file_path = os.path.join(data_path, foldName, foldName+'.aedat4')
save_img_path = os.path.join(save_path, foldName, foldName+'_recon')
if not os.path.exists(save_img_path):
os.makedirs(save_img_path)
# dvs_img_interval = 1
# for root, dirs, files in os.walk(aedat_path):
# for file in files:
# (filename, extension) = os.path.splitext(file)
# print("==>> filename: ", filename)
# if (extension == '.aedat4'):
# if filename + '_aps' in os.listdir(root) or filename + '_dvs' in os.listdir(root):
# print("==>> Skip this video ... ")
# continue
# save_path_dvs = os.path.join(root, filename, filename+'_dvs')
# save_path_aps = os.path.join(root, filename, filename+'_aps')
# aedat_file_path = os.path.join(root, filename + '.aedat4')
# filename_txt_path = os.path.join(root, filename+'_timestamp.txt')
# croped_events_path = os.path.join(root, filename+'_events.txt')
# if not os.path.exists(save_path_dvs):
# os.makedirs(save_path_dvs)
# if not os.path.exists(save_path_aps):
# os.makedirs(save_path_aps)
timestamps, x, y, polarities, frame_num, frame_timestamp = extract_davis(aedat_file_path, 1) ## (4391964,)
# all_events = [timestamps, x, y, polarities]
all_events = np.zeros((timestamps.shape[0], 4))
all_events[:, 0] = timestamps
all_events[:, 1] = x
all_events[:, 2] = y
all_events[:, 3] = polarities
# pdb.set_trace()
parser = argparse.ArgumentParser(description='Evaluating a trained network')
parser.add_argument('-c', '--path_to_model', required=True, type=str, help='path to model weights')
parser.add_argument('-i', '--input_file', required=False, type=str)
parser.add_argument('--fixed_duration', dest='fixed_duration', action='store_true')
parser.set_defaults(fixed_duration=False)
parser.add_argument('-N', '--window_size', default=500000, type=int,
help="Size of each event window, in number of events. Ignored if --fixed_duration=True")
parser.add_argument('-T', '--window_duration', default=33.33, type=float,
help="Duration of each event window, in milliseconds. Ignored if --fixed_duration=False")
parser.add_argument('--num_events_per_pixel', default=0.35, type=float,
help='in case N (window size) is not specified, it will be automatically computed as N = width * height * num_events_per_pixel')
parser.add_argument('--skipevents', default=0, type=int)
parser.add_argument('--suboffset', default=0, type=int)
parser.add_argument('--compute_voxel_grid_on_cpu', dest='compute_voxel_grid_on_cpu',
action='store_true')
parser.set_defaults(compute_voxel_grid_on_cpu=False)
set_inference_options(parser)
args = parser.parse_args()
# Load model
device = get_device(args.use_gpu)
model = load_model(args.path_to_model, device)
# model = load_model(args.path_to_model)
model = model.to(device)
model.eval()
# pdb.set_trace()
height, width = 260, 346
reconstructor = ImageReconstructor(model, height, width, model.num_bins, args)
start_s = 0
""" Read chunks of events using Pandas """
for frame_no in range(0, frame_num-1):
# Loop through the events and reconstruct images
N = frame_timestamp[frame_no][1] - frame_timestamp[frame_no][0]
# if not args.fixed_duration:
# if N is None:
# N = int(width * height * args.num_events_per_pixel)
# print(
# 'Will use {} events per tensor (automatically estimated with num_events_per_pixel={:0.2f}).'.format(
# N, args.num_events_per_pixel))
# else:
# print('Will use {} events per tensor (user-specified)'.format(N))
# mean_num_events_per_pixel = float(N) / float(width * height)
# if mean_num_events_per_pixel < 0.1:
# print('!!Warning!! the number of events used ({}) seems to be low compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
# elif mean_num_events_per_pixel > 1.5:
# print('!!Warning!! the number of events used ({}) seems to be high compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
initial_offset = args.skipevents
sub_offset = args.suboffset
start_index = initial_offset + sub_offset
if args.compute_voxel_grid_on_cpu:
print('Will compute voxel grid on CPU.')
with Timer('Processing entire dataset'):
# event_window = all_events[:N, :]
# event_window = all_events[start_s: start_s+N, :]
# last_timestamp = event_window[-1, 0]
# start_s += N
start_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][0])[0][0]
end_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][1])[0][0]
event_window = all_events[start_idx:end_idx]
last_timestamp = event_window[-1, 0]
with Timer('Building event tensor'):
if args.compute_voxel_grid_on_cpu:
# pdb.set_trace()
event_tensor = events_to_voxel_grid(event_window, num_bins=model.num_bins, width=width,
height=height)
event_tensor = torch.from_numpy(event_tensor)
else:
# pdb.set_trace()
event_tensor = events_to_voxel_grid_pytorch(event_window, num_bins=model.num_bins,
width=width, height=height, device=device)
num_events_in_window = event_window.shape[0]
# reconstructor.update_reconstruction(event_tensor, start_index + num_events_in_window,
# last_timestamp, frame_no, save_img_path)
reconstructor.update_reconstruction(event_tensor, frame_no, last_timestamp)
start_index += num_events_in_window
② import torch
import cv2
import numpy as np
from model.model import *
from utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter
from utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction
from utils.util import robust_min, robust_max
from utils.timers import CudaTimer, cuda_timers
from os.path import join
from collections import deque
import torch.nn.functional as F
class ImageReconstructor:
def init(self, model, height, width, num_bins, options):
code
self.model = model
self.use_gpu = options.use_gpu
self.device = torch.device('cuda:0') if self.use_gpu else torch.device('cpu')
self.height = height
self.width = width
self.num_bins = num_bins
self.initialize(self.height, self.width, options)
def initialize(self, height, width, options):
print('== Image reconstruction == ')
print('Image size: {}x{}'.format(self.height, self.width))
self.no_recurrent = options.no_recurrent
if self.no_recurrent:
print('!!Recurrent connection disabled!!')
self.perform_color_reconstruction = options.color # whether to perform color reconstruction (only use this with the DAVIS346color)
if self.perform_color_reconstruction:
if options.auto_hdr:
print('!!Warning: disabling auto HDR for color reconstruction!!')
options.auto_hdr = False # disable auto_hdr for color reconstruction (otherwise, each channel will be normalized independently)
self.crop = CropParameters(self.width, self.height, self.model.num_encoders)
self.last_states_for_each_channel = {'grayscale': None}
if self.perform_color_reconstruction:
self.crop_halfres = CropParameters(int(width / 2), int(height / 2),
self.model.num_encoders)
for channel in ['R', 'G', 'B', 'W']:
self.last_states_for_each_channel[channel] = None
self.event_preprocessor = EventPreprocessor(options)
self.intensity_rescaler = IntensityRescaler(options)
self.image_filter = ImageFilter(options)
self.unsharp_mask_filter = UnsharpMaskFilter(options, device=self.device)
self.image_writer = ImageWriter(options)
self.image_display = ImageDisplay(options)
def update_reconstruction(self, event_tensor, event_tensor_id, stamp=None):
with torch.no_grad():
with CudaTimer('Reconstruction'):
with CudaTimer('NumPy (CPU) -> Tensor (GPU)'):
events = event_tensor.unsqueeze(dim=0)
events = events.to(self.device)
events = self.event_preprocessor(events)
# Resize tensor to [1 x C x crop_size x crop_size] by applying zero padding
events_for_each_channel = {'grayscale': self.crop.pad(events)}
reconstructions_for_each_channel = {}
if self.perform_color_reconstruction:
events_for_each_channel['R'] = self.crop_halfres.pad(events[:, :, 0::2, 0::2])
events_for_each_channel['G'] = self.crop_halfres.pad(events[:, :, 0::2, 1::2])
events_for_each_channel['W'] = self.crop_halfres.pad(events[:, :, 1::2, 0::2])
events_for_each_channel['B'] = self.crop_halfres.pad(events[:, :, 1::2, 1::2])
# Reconstruct new intensity image for each channel (grayscale + RGBW if color reconstruction is enabled)
for channel in events_for_each_channel.keys():
with CudaTimer('Inference'):
new_predicted_frame, states = self.model(events_for_each_channel[channel],
self.last_states_for_each_channel[channel])
if self.no_recurrent:
self.last_states_for_each_channel[channel] = None
else:
self.last_states_for_each_channel[channel] = states
# Output reconstructed image
crop = self.crop if channel == 'grayscale' else self.crop_halfres
# Unsharp mask (on GPU)
new_predicted_frame = self.unsharp_mask_filter(new_predicted_frame)
# Intensity rescaler (on GPU)
new_predicted_frame = self.intensity_rescaler(new_predicted_frame)
with CudaTimer('Tensor (GPU) -> NumPy (CPU)'):
reconstructions_for_each_channel[channel] = new_predicted_frame[0, 0, crop.iy0:crop.iy1,
crop.ix0:crop.ix1].cpu().numpy()
if self.perform_color_reconstruction:
out = merge_channels_into_color_image(reconstructions_for_each_channel)
else:
out = reconstructions_for_each_channel['grayscale']
# Post-processing, e.g bilateral filter (on CPU)
out = self.image_filter(out)
self.image_writer(out, event_tensor_id, stamp, events=events)
self.image_display(out, events)
那么针对上个问题,应该如何设置和修改?
Main Function
#######################################################################################################
if name == "main":
device = torch.device("cuda:0")
# data_path = r"/home/ioe/xxxxx/EventTracking/COESOT/train"
data_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
save_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
video_files = os.listdir(data_path)
# 由于数据集中有txt文件,因此需要排除
video_files = [file for file in video_files if file not in ('list.txt', 'train.txt')]
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
code
aedat_file_path = os.path.join(data_path, foldName, foldName+'.aedat4')
save_img_path = os.path.join(save_path, foldName, foldName+'_recon')
if not os.path.exists(save_img_path):
os.makedirs(save_img_path)
# dvs_img_interval = 1
# for root, dirs, files in os.walk(aedat_path):
# for file in files:
# (filename, extension) = os.path.splitext(file)
# print("==>> filename: ", filename)
# if (extension == '.aedat4'):
# if filename + '_aps' in os.listdir(root) or filename + '_dvs' in os.listdir(root):
# print("==>> Skip this video ... ")
# continue
# save_path_dvs = os.path.join(root, filename, filename+'_dvs')
# save_path_aps = os.path.join(root, filename, filename+'_aps')
# aedat_file_path = os.path.join(root, filename + '.aedat4')
# filename_txt_path = os.path.join(root, filename+'_timestamp.txt')
# croped_events_path = os.path.join(root, filename+'_events.txt')
# if not os.path.exists(save_path_dvs):
# os.makedirs(save_path_dvs)
# if not os.path.exists(save_path_aps):
# os.makedirs(save_path_aps)
timestamps, x, y, polarities, frame_num, frame_timestamp = extract_davis(aedat_file_path, 1) ## (4391964,)
# all_events = [timestamps, x, y, polarities]
all_events = np.zeros((timestamps.shape[0], 4))
all_events[:, 0] = timestamps
all_events[:, 1] = x
all_events[:, 2] = y
all_events[:, 3] = polarities
# pdb.set_trace()
parser = argparse.ArgumentParser(description='Evaluating a trained network')
parser.add_argument('-c', '--path_to_model', required=True, type=str, help='path to model weights')
parser.add_argument('-i', '--input_file', required=True, type=str)
parser.add_argument('--fixed_duration', dest='fixed_duration', action='store_true')
parser.set_defaults(fixed_duration=False)
parser.add_argument('-N', '--window_size', default=500000, type=int,
help="Size of each event window, in number of events. Ignored if --fixed_duration=True")
parser.add_argument('-T', '--window_duration', default=33.33, type=float,
help="Duration of each event window, in milliseconds. Ignored if --fixed_duration=False")
parser.add_argument('--num_events_per_pixel', default=0.35, type=float,
help='in case N (window size) is not specified, it will be automatically computed as N = width * height * num_events_per_pixel')
parser.add_argument('--skipevents', default=0, type=int)
parser.add_argument('--suboffset', default=0, type=int)
parser.add_argument('--compute_voxel_grid_on_cpu', dest='compute_voxel_grid_on_cpu',
action='store_true')
parser.set_defaults(compute_voxel_grid_on_cpu=False)
set_inference_options(parser)
args = parser.parse_args()
# Load model
device = get_device(args.use_gpu)
model = load_model(args.path_to_model, device)
model = model.to(device)
model.eval()
# pdb.set_trace()
height, width = 260, 346
reconstructor = ImageReconstructor(model, height, width, model.num_bins, args)
start_s = 0
""" Read chunks of events using Pandas """
for frame_no in range(0, frame_num-1):
# Loop through the events and reconstruct images
N = frame_timestamp[frame_no][1] - frame_timestamp[frame_no][0]
# if not args.fixed_duration:
# if N is None:
# N = int(width * height * args.num_events_per_pixel)
# print(
# 'Will use {} events per tensor (automatically estimated with num_events_per_pixel={:0.2f}).'.format(
# N, args.num_events_per_pixel))
# else:
# print('Will use {} events per tensor (user-specified)'.format(N))
# mean_num_events_per_pixel = float(N) / float(width * height)
# if mean_num_events_per_pixel < 0.1:
# print('!!Warning!! the number of events used ({}) seems to be low compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
# elif mean_num_events_per_pixel > 1.5:
# print('!!Warning!! the number of events used ({}) seems to be high compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
initial_offset = args.skipevents
sub_offset = args.suboffset
start_index = initial_offset + sub_offset
if args.compute_voxel_grid_on_cpu:
print('Will compute voxel grid on CPU.')
with Timer('Processing entire dataset'):
# event_window = all_events[:N, :]
# event_window = all_events[start_s: start_s+N, :]
# last_timestamp = event_window[-1, 0]
# start_s += N
start_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][0])[0][0]
end_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][1])[0][0]
event_window = all_events[start_idx:end_idx]
last_timestamp = event_window[-1, 0]
with Timer('Building event tensor'):
if args.compute_voxel_grid_on_cpu:
# pdb.set_trace()
event_tensor = events_to_voxel_grid(event_window, num_bins=model.num_bins, width=width,
height=height)
event_tensor = torch.from_numpy(event_tensor)
else:
# pdb.set_trace()
event_tensor = events_to_voxel_grid_pytorch(event_window, num_bins=model.num_bins,
width=width, height=height, device=device)
num_events_in_window = event_window.shape[0]
reconstructor.update_reconstruction(event_tensor, start_index + num_events_in_window,
last_timestamp, frame_no, save_img_path)
start_index += num_events_in_window
中是否会将生成的文件写入磁盘?
def __init__(self, options):
print('== Event preprocessing ==')
self.no_normalize = options.no_normalize
if self.no_normalize:
print('!!Will not normalize event tensors!!')
else:
print('Will normalize event tensors.')
self.hot_pixel_locations = []
if options.hot_pixels_file:
try:
self.hot_pixel_locations = np.loadtxt(options.hot_pixels_file, delimiter=',').astype(np.int)
print('Will remove {} hot pixels'.format(self.hot_pixel_locations.shape[0]))
except IOError:
print('WARNING: could not load hot pixels file: {}'.format(options.hot_pixels_file))
self.flip = options.flip
if self.flip:
print('Will flip event tensors.')
def __call__(self, events):
# Remove (i.e. zero out) the hot pixels
for x, y in self.hot_pixel_locations:
events[:, :, y, x] = 0
# Flip tensor vertically and horizontally
if self.flip:
events = torch.flip(events, dims=[2, 3])
# Normalize the event tensor (voxel grid) so that
# the mean and stddev of the nonzero values in the tensor are equal to (0.0, 1.0)
if not self.no_normalize:
with CudaTimer('Normalization'):
nonzero_ev = (events != 0)
num_nonzeros = nonzero_ev.sum()
if num_nonzeros > 0:
# compute mean and stddev of the **nonzero** elements of the event tensor
# we do not use PyTorch's default mean() and std() functions since it's faster
# to compute it by hand than applying those funcs to a masked array
mean = events.sum() / num_nonzeros
stddev = torch.sqrt((events ** 2).sum() / num_nonzeros - mean ** 2)
mask = nonzero_ev.float()
events = mask * (events - mean) / stddev
return events
class IntensityRescaler:
"""
Utility class to rescale image intensities to the range [0, 1],
using (robust) min/max normalization.
Optionally, the min/max bounds can be smoothed over a sliding window to avoid jitter.
"""
code
def __init__(self, options):
self.auto_hdr = options.auto_hdr
self.intensity_bounds = deque()
self.auto_hdr_median_filter_size = options.auto_hdr_median_filter_size
self.Imin = options.Imin
self.Imax = options.Imax
def __call__(self, img):
"""
param img: [1 x 1 x H x W] Tensor taking values in [0, 1]
"""
if self.auto_hdr:
with CudaTimer('Compute Imin/Imax (auto HDR)'):
Imin = torch.min(img).item()
Imax = torch.max(img).item()
# ensure that the range is at least 0.1
Imin = np.clip(Imin, 0.0, 0.45)
Imax = np.clip(Imax, 0.55, 1.0)
# adjust image dynamic range (i.e. its contrast)
if len(self.intensity_bounds) > self.auto_hdr_median_filter_size:
self.intensity_bounds.popleft()
self.intensity_bounds.append((Imin, Imax))
self.Imin = np.median([rmin for rmin, rmax in self.intensity_bounds])
self.Imax = np.median([rmax for rmin, rmax in self.intensity_bounds])
with CudaTimer('Intensity rescaling'):
img = 255.0 * (img - self.Imin) / (self.Imax - self.Imin)
img.clamp_(0.0, 255.0)
img = img.byte() # convert to 8-bit tensor
return img
class ImageWriter:
"""
Utility class to write images to disk.
Also writes the image timestamps into a text file.
"""
code
def __init__(self, options):
self.output_folder = options.output_folder
self.dataset_name = options.dataset_name
self.save_events = options.show_events
self.event_display_mode = options.event_display_mode
self.num_bins_to_show = options.num_bins_to_show
print('== Image Writer ==')
if self.output_folder:
ensure_dir(self.output_folder)
ensure_dir(join(self.output_folder, self.dataset_name))
print('Will write images to: {}'.format(join(self.output_folder, self.dataset_name)))
self.timestamps_file = open(join(self.output_folder, self.dataset_name, 'timestamps.txt'), 'a')
if self.save_events:
self.event_previews_folder = join(self.output_folder, self.dataset_name, 'events')
ensure_dir(self.event_previews_folder)
print('Will write event previews to: {}'.format(self.event_previews_folder))
atexit.register(self.__cleanup__)
else:
print('Will not write images to disk.')
def __call__(self, img, event_tensor_id, stamp=None, events=None):
if not self.output_folder:
return
if self.save_events and events is not None:
event_preview = make_event_preview(events, mode=self.event_display_mode,
num_bins_to_show=self.num_bins_to_show)
cv2.imwrite(join(self.event_previews_folder,
'events_{:010d}.png'.format(event_tensor_id)), event_preview)
cv2.imwrite(join(self.output_folder, self.dataset_name,
'frame_{:010d}.png'.format(event_tensor_id)), img)
if stamp is not None:
self.timestamps_file.write('{:.18f}\n'.format(stamp))
def __cleanup__(self):
if self.output_folder:
self.timestamps_file.close()
class ImageDisplay:
"""
Utility class to display image reconstructions
"""
code
def __init__(self, options):
self.display = options.display
self.show_events = options.show_events
self.color = options.color
self.event_display_mode = options.event_display_mode
self.num_bins_to_show = options.num_bins_to_show
self.window_name = 'Reconstruction'
if self.show_events:
self.window_name = 'Events | ' + self.window_name
if self.display:
cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
self.border = options.display_border_crop
self.wait_time = options.display_wait_time
def crop_outer_border(self, img, border):
if self.border == 0:
return img
else:
return img[border:-border, border:-border]
def __call__(self, img, events=None):
if not self.display:
return
img = self.crop_outer_border(img, self.border)
if self.show_events:
assert(events is not None)
event_preview = make_event_preview(events, mode=self.event_display_mode,
num_bins_to_show=self.num_bins_to_show)
event_preview = self.crop_outer_border(event_preview, self.border)
if self.show_events:
img_is_color = (len(img.shape) == 3)
preview_is_color = (len(event_preview.shape) == 3)
if(preview_is_color and not img_is_color):
img = np.dstack([img] * 3)
elif(img_is_color and not preview_is_color):
event_preview = np.dstack([event_preview] * 3)
img = np.hstack([event_preview, img])
cv2.imshow(self.window_name, img)
cv2.waitKey(self.wait_time)
class UnsharpMaskFilter:
"""
Utility class to perform unsharp mask filtering on reconstructed images.
"""
def optimal_crop_size(max_size, max_subsample_factor):
""" Find the optimal crop size for a given max_size and subsample_factor.
The optimal crop size is the smallest integer which is greater or equal than max_size,
while being divisible by 2^max_subsample_factor.
"""
crop_size = int(pow(2, max_subsample_factor) * ceil(max_size / pow(2, max_subsample_factor)))
return crop_size
class CropParameters:
""" Helper class to compute and store useful parameters for pre-processing and post-processing
of images in and out of E2VID.
Pre-processing: finding the best image size for the network, and padding the input image with zeros
Post-processing: Crop the output image back to the original image size
"""
def shift_image(X, dx, dy):
X = np.roll(X, dy, axis=0)
X = np.roll(X, dx, axis=1)
if dy > 0:
X[:dy, :] = np.expand_dims(X[dy, :], axis=0)
elif dy < 0:
X[dy:, :] = np.expand_dims(X[dy, :], axis=0)
if dx > 0:
X[:, :dx] = np.expand_dims(X[:, dx], axis=1)
elif dx < 0:
X[:, dx:] = np.expand_dims(X[:, dx], axis=1)
return X
def upsample_color_image(grayscale_highres, color_lowres_bgr, colorspace='LAB'):
"""
Generate a high res color image from a high res grayscale image, and a low res color image,
using the trick described in:
http://www.planetary.org/blogs/emily-lakdawalla/2013/04231204-image-processing-colorizing-images.html
"""
assert(len(grayscale_highres.shape) == 2)
assert(len(color_lowres_bgr.shape) == 3 and color_lowres_bgr.shape[2] == 3)
code
if colorspace == 'LAB':
# convert color image to LAB space
lab = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2LAB)
# replace lightness channel with the highres image
lab[:, :, 0] = grayscale_highres
# convert back to BGR
color_highres_bgr = cv2.cvtColor(src=lab, code=cv2.COLOR_LAB2BGR)
elif colorspace == 'HSV':
# convert color image to HSV space
hsv = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2HSV)
# replace value channel with the highres image
hsv[:, :, 2] = grayscale_highres
# convert back to BGR
color_highres_bgr = cv2.cvtColor(src=hsv, code=cv2.COLOR_HSV2BGR)
elif colorspace == 'HLS':
# convert color image to HLS space
hls = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2HLS)
# replace lightness channel with the highres image
hls[:, :, 1] = grayscale_highres
# convert back to BGR
color_highres_bgr = cv2.cvtColor(src=hls, code=cv2.COLOR_HLS2BGR)
return color_highres_bgr
def merge_channels_into_color_image(channels):
"""
Combine a full resolution grayscale reconstruction and four color channels at half resolution
into a color image at full resolution.
code
:param channels: dictionary containing the four color reconstructions (at quarter resolution),
and the full resolution grayscale reconstruction.
:return a color image at full resolution
"""
with Timer('Merge color channels'):
assert('R' in channels)
assert('G' in channels)
assert('W' in channels)
assert('B' in channels)
assert('grayscale' in channels)
# upsample each channel independently
for channel in ['R', 'G', 'W', 'B']:
channels[channel] = cv2.resize(channels[channel], dsize=None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
# Shift the channels so that they all have the same origin
channels['B'] = shift_image(channels['B'], dx=1, dy=1)
channels['G'] = shift_image(channels['G'], dx=1, dy=0)
channels['W'] = shift_image(channels['W'], dx=0, dy=1)
# reconstruct the color image at half the resolution using the reconstructed channels RGBW
reconstruction_bgr = np.dstack([channels['B'],
cv2.addWeighted(src1=channels['G'], alpha=0.5,
src2=channels['W'], beta=0.5,
gamma=0.0, dtype=cv2.CV_8U),
channels['R']])
reconstruction_grayscale = channels['grayscale']
# combine the full res grayscale resolution with the low res to get a full res color image
upsampled_img = upsample_color_image(reconstruction_grayscale, reconstruction_bgr)
return upsampled_img
return upsampled_img
def events_to_voxel_grid(events, num_bins, width, height):
"""
Build a voxel grid with bilinear interpolation in the time domain from a set of events.
code
:param events: a [N x 4] NumPy array containing one event per row in the form: [timestamp, x, y, polarity]
:param num_bins: number of bins in the temporal axis of the voxel grid
:param width, height: dimensions of the voxel grid
"""
assert(events.shape[1] == 4)
assert(num_bins > 0)
assert(width > 0)
assert(height > 0)
voxel_grid = np.zeros((num_bins, height, width), np.float32).ravel()
# normalize the event timestamps so that they lie between 0 and num_bins
last_stamp = events[-1, 0]
first_stamp = events[0, 0]
deltaT = last_stamp - first_stamp
if deltaT == 0:
deltaT = 1.0
events[:, 0] = (num_bins - 1) * (events[:, 0] - first_stamp) / deltaT
ts = events[:, 0]
xs = events[:, 1].astype(np.int)
ys = events[:, 2].astype(np.int)
pols = events[:, 3]
pols[pols == 0] = -1 # polarity should be +1 / -1
tis = ts.astype(np.int)
dts = ts - tis
vals_left = pols * (1.0 - dts)
vals_right = pols * dts
valid_indices = tis < num_bins
np.add.at(voxel_grid, xs[valid_indices] + ys[valid_indices] * width
+ tis[valid_indices] * width * height, vals_left[valid_indices])
valid_indices = (tis + 1) < num_bins
np.add.at(voxel_grid, xs[valid_indices] + ys[valid_indices] * width
+ (tis[valid_indices] + 1) * width * height, vals_right[valid_indices])
voxel_grid = np.reshape(voxel_grid, (num_bins, height, width))
return voxel_grid
Build a voxel grid with bilinear interpolation in the time domain from a set of events.
:param events: a [N x 4] NumPy array containing one event per row in the form: [timestamp, x, y, polarity]
:param num_bins: number of bins in the temporal axis of the voxel grid
:param width, height: dimensions of the voxel grid
:param device: device to use to perform computations
:return voxel_grid: PyTorch event tensor (on the device specified)
"""
DeviceTimer = CudaTimer if device.type == 'cuda' else Timer
assert(events.shape[1] == 4)
assert(num_bins > 0)
assert(width > 0)
assert(height > 0)
with torch.no_grad():
events_torch = torch.from_numpy(events)
with DeviceTimer('Events -> Device (voxel grid)'):
events_torch = events_torch.to(device)
with DeviceTimer('Voxel grid voting'):
voxel_grid = torch.zeros(num_bins, height, width, dtype=torch.float32, device=device).flatten()
# normalize the event timestamps so that they lie between 0 and num_bins
last_stamp = events_torch[-1, 0]
first_stamp = events_torch[0, 0]
deltaT = last_stamp - first_stamp
if deltaT == 0:
deltaT = 1.0
events_torch[:, 0] = (num_bins - 1) * (events_torch[:, 0] - first_stamp) / deltaT
ts = events_torch[:, 0]
xs = events_torch[:, 1].long()
ys = events_torch[:, 2].long()
pols = events_torch[:, 3].float()
pols[pols == 0] = -1 # polarity should be +1 / -1
tis = torch.floor(ts)
tis_long = tis.long()
dts = ts - tis
vals_left = pols * (1.0 - dts.float())
vals_right = pols * dts.float()
valid_indices = tis < num_bins
valid_indices &= tis >= 0
voxel_grid.index_add_(dim=0,
index=xs[valid_indices] + ys[valid_indices]
* width + tis_long[valid_indices] * width * height,
source=vals_left[valid_indices])
valid_indices = (tis + 1) < num_bins
valid_indices &= tis >= 0
voxel_grid.index_add_(dim=0,
index=xs[valid_indices] + ys[valid_indices] * width
+ (tis_long[valid_indices] + 1) * width * height,
source=vals_right[valid_indices])
voxel_grid = voxel_grid.view(num_bins, height, width)
return voxel_grid
# pdb.set_trace()
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)
# Access dimensions of the event stream
height, width = f['events'].size # 260 346
event_frame = 255 * np.ones((height, width, 3), dtype=np.uint8)
# loop through the "events" stream
# events = np.hstack([packet for packet in f['events'].numpy()])
# # Access information of all events by type
# timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
# pdb.set_trace()
# save event_img
idx = np.round(np.linspace(0, len(frame_timestamp) - 1, int(frame_num / dvs_img_interval))).astype(
int) ## frame index [0, 1, 2, ... , 3847]
frame_timestamp = np.array(frame_timestamp)[idx] ## (3848, 2)
# another reader # speed up
# events will be a named numpy array
events = np.hstack([packet for packet in f['events'].numpy()])
timestamps, x, y, polarities = events['timestamp'], events['x'], events['y'], events['polarity']
return timestamps, x, y, polarities, frame_num, frame_timestamp
#######################################################################################################
Main Function
#######################################################################################################
if name == "main":
device = torch.device("cuda:0")
# data_path = r"/home/ioe/xxxxx/EventTracking/COESOT/train"
data_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
save_path = r"/data2/local_userdata/heyuting/datasets/COESOT/train"
video_files = os.listdir(data_path)
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
code
if foldName not in ['dvSave-2021_12_21_11_53_57']:
continue
aedat_file_path = os.path.join(data_path, foldName, foldName+'.aedat4')
save_img_path = os.path.join(save_path, foldName, foldName+'_recon')
if not os.path.exists(save_img_path):
os.makedirs(save_img_path)
# dvs_img_interval = 1
# for root, dirs, files in os.walk(aedat_path):
# for file in files:
# (filename, extension) = os.path.splitext(file)
# print("==>> filename: ", filename)
# if (extension == '.aedat4'):
# if filename + '_aps' in os.listdir(root) or filename + '_dvs' in os.listdir(root):
# print("==>> Skip this video ... ")
# continue
# save_path_dvs = os.path.join(root, filename, filename+'_dvs')
# save_path_aps = os.path.join(root, filename, filename+'_aps')
# aedat_file_path = os.path.join(root, filename + '.aedat4')
# filename_txt_path = os.path.join(root, filename+'_timestamp.txt')
# croped_events_path = os.path.join(root, filename+'_events.txt')
# if not os.path.exists(save_path_dvs):
# os.makedirs(save_path_dvs)
# if not os.path.exists(save_path_aps):
# os.makedirs(save_path_aps)
timestamps, x, y, polarities, frame_num, frame_timestamp = extract_davis(aedat_file_path, 1) ## (4391964,)
# all_events = [timestamps, x, y, polarities]
all_events = np.zeros((timestamps.shape[0], 4))
all_events[:, 0] = timestamps
all_events[:, 1] = x
all_events[:, 2] = y
all_events[:, 3] = polarities
# pdb.set_trace()
parser = argparse.ArgumentParser(description='Evaluating a trained network')
parser.add_argument('-c', '--path_to_model', required=True, type=str, help='path to model weights')
parser.add_argument('-i', '--input_file', required=False, type=str)
parser.add_argument('--fixed_duration', dest='fixed_duration', action='store_true')
parser.set_defaults(fixed_duration=False)
parser.add_argument('-N', '--window_size', default=500000, type=int,
help="Size of each event window, in number of events. Ignored if --fixed_duration=True")
parser.add_argument('-T', '--window_duration', default=33.33, type=float,
help="Duration of each event window, in milliseconds. Ignored if --fixed_duration=False")
parser.add_argument('--num_events_per_pixel', default=0.35, type=float,
help='in case N (window size) is not specified, it will be automatically computed as N = width * height * num_events_per_pixel')
parser.add_argument('--skipevents', default=0, type=int)
parser.add_argument('--suboffset', default=0, type=int)
parser.add_argument('--compute_voxel_grid_on_cpu', dest='compute_voxel_grid_on_cpu',
action='store_true')
parser.set_defaults(compute_voxel_grid_on_cpu=False)
set_inference_options(parser)
args = parser.parse_args()
# Load model
device = get_device(args.use_gpu)
model = load_model(args.path_to_model, device)
# model = load_model(args.path_to_model)
model = model.to(device)
model.eval()
# pdb.set_trace()
height, width = 260, 346
reconstructor = ImageReconstructor(model, height, width, model.num_bins, args)
start_s = 0
""" Read chunks of events using Pandas """
for frame_no in range(0, frame_num-1):
# Loop through the events and reconstruct images
N = frame_timestamp[frame_no][1] - frame_timestamp[frame_no][0]
# if not args.fixed_duration:
# if N is None:
# N = int(width * height * args.num_events_per_pixel)
# print(
# 'Will use {} events per tensor (automatically estimated with num_events_per_pixel={:0.2f}).'.format(
# N, args.num_events_per_pixel))
# else:
# print('Will use {} events per tensor (user-specified)'.format(N))
# mean_num_events_per_pixel = float(N) / float(width * height)
# if mean_num_events_per_pixel < 0.1:
# print('!!Warning!! the number of events used ({}) seems to be low compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
# elif mean_num_events_per_pixel > 1.5:
# print('!!Warning!! the number of events used ({}) seems to be high compared to the sensor size. \
# The reconstruction results might be suboptimal.'.format(N))
initial_offset = args.skipevents
sub_offset = args.suboffset
start_index = initial_offset + sub_offset
if args.compute_voxel_grid_on_cpu:
print('Will compute voxel grid on CPU.')
with Timer('Processing entire dataset'):
# event_window = all_events[:N, :]
# event_window = all_events[start_s: start_s+N, :]
# last_timestamp = event_window[-1, 0]
# start_s += N
start_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][0])[0][0]
end_idx = np.where(all_events[:, 0] >= frame_timestamp[frame_no][1])[0][0]
event_window = all_events[start_idx:end_idx]
last_timestamp = event_window[-1, 0]
with Timer('Building event tensor'):
if args.compute_voxel_grid_on_cpu:
# pdb.set_trace()
event_tensor = events_to_voxel_grid(event_window, num_bins=model.num_bins, width=width,
height=height)
event_tensor = torch.from_numpy(event_tensor)
else:
# pdb.set_trace()
event_tensor = events_to_voxel_grid_pytorch(event_window, num_bins=model.num_bins,
width=width, height=height, device=device)
num_events_in_window = event_window.shape[0]
reconstructor.update_reconstruction(event_tensor, start_index + num_events_in_window,
last_timestamp, frame_no, save_img_path)
# reconstructor.update_reconstruction(event_tensor, frame_no, last_timestamp)
start_index += num_events_in_window
,那么需要如何修改:import torch
import cv2
import numpy as np
from model.model import *
from utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter
from utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction
from utils.util import robust_min, robust_max
from utils.timers import CudaTimer, cuda_timers
from os.path import join
from collections import deque
import torch.nn.functional as F
class ImageReconstructor:
def init(self, model, height, width, num_bins, options):
code
self.model = model
self.use_gpu = options.use_gpu
self.device = torch.device('cuda:0') if self.use_gpu else torch.device('cpu')
self.height = height
self.width = width
self.num_bins = num_bins
self.initialize(self.height, self.width, options)
def initialize(self, height, width, options):
print('== Image reconstruction == ')
print('Image size: {}x{}'.format(self.height, self.width))
self.no_recurrent = options.no_recurrent
if self.no_recurrent:
print('!!Recurrent connection disabled!!')
self.perform_color_reconstruction = options.color # whether to perform color reconstruction (only use this with the DAVIS346color)
if self.perform_color_reconstruction:
if options.auto_hdr:
print('!!Warning: disabling auto HDR for color reconstruction!!')
options.auto_hdr = False # disable auto_hdr for color reconstruction (otherwise, each channel will be normalized independently)
self.crop = CropParameters(self.width, self.height, self.model.num_encoders)
self.last_states_for_each_channel = {'grayscale': None}
if self.perform_color_reconstruction:
self.crop_halfres = CropParameters(int(width / 2), int(height / 2),
self.model.num_encoders)
for channel in ['R', 'G', 'B', 'W']:
self.last_states_for_each_channel[channel] = None
self.event_preprocessor = EventPreprocessor(options)
self.intensity_rescaler = IntensityRescaler(options)
self.image_filter = ImageFilter(options)
self.unsharp_mask_filter = UnsharpMaskFilter(options, device=self.device)
self.image_writer = ImageWriter(options)
self.image_display = ImageDisplay(options)
def update_reconstruction(self, event_tensor, event_tensor_id, stamp=None):
with torch.no_grad():
with CudaTimer('Reconstruction'):
with CudaTimer('NumPy (CPU) -> Tensor (GPU)'):
events = event_tensor.unsqueeze(dim=0)
events = events.to(self.device)
events = self.event_preprocessor(events)
# Resize tensor to [1 x C x crop_size x crop_size] by applying zero padding
events_for_each_channel = {'grayscale': self.crop.pad(events)}
reconstructions_for_each_channel = {}
if self.perform_color_reconstruction:
events_for_each_channel['R'] = self.crop_halfres.pad(events[:, :, 0::2, 0::2])
events_for_each_channel['G'] = self.crop_halfres.pad(events[:, :, 0::2, 1::2])
events_for_each_channel['W'] = self.crop_halfres.pad(events[:, :, 1::2, 0::2])
events_for_each_channel['B'] = self.crop_halfres.pad(events[:, :, 1::2, 1::2])
# Reconstruct new intensity image for each channel (grayscale + RGBW if color reconstruction is enabled)
for channel in events_for_each_channel.keys():
with CudaTimer('Inference'):
new_predicted_frame, states = self.model(events_for_each_channel[channel],
self.last_states_for_each_channel[channel])
if self.no_recurrent:
self.last_states_for_each_channel[channel] = None
else:
self.last_states_for_each_channel[channel] = states
# Output reconstructed image
crop = self.crop if channel == 'grayscale' else self.crop_halfres
# Unsharp mask (on GPU)
new_predicted_frame = self.unsharp_mask_filter(new_predicted_frame)
# Intensity rescaler (on GPU)
new_predicted_frame = self.intensity_rescaler(new_predicted_frame)
with CudaTimer('Tensor (GPU) -> NumPy (CPU)'):
reconstructions_for_each_channel[channel] = new_predicted_frame[0, 0, crop.iy0:crop.iy1,
crop.ix0:crop.ix1].cpu().numpy()
if self.perform_color_reconstruction:
out = merge_channels_into_color_image(reconstructions_for_each_channel)
else:
out = reconstructions_for_each_channel['grayscale']
# Post-processing, e.g bilateral filter (on CPU)
out = self.image_filter(out)
self.image_writer(out, event_tensor_id, stamp, events=events)
self.image_display(out, events)
self.model = model
self.use_gpu = options.use_gpu
self.device = torch.device('cuda:0') if self.use_gpu else torch.device('cpu')
self.height = height
self.width = width
self.num_bins = num_bins
self.initialize(self.height, self.width, options)
def initialize(self, height, width, options):
print('== Image reconstruction == ')
print('Image size: {}x{}'.format(self.height, self.width))
self.no_recurrent = options.no_recurrent
if self.no_recurrent:
print('!!Recurrent connection disabled!!')
self.perform_color_reconstruction = options.color # whether to perform color reconstruction (only use this with the DAVIS346color)
if self.perform_color_reconstruction:
if options.auto_hdr:
print('!!Warning: disabling auto HDR for color reconstruction!!')
options.auto_hdr = False # disable auto_hdr for color reconstruction (otherwise, each channel will be normalized independently)
self.crop = CropParameters(self.width, self.height, self.model.num_encoders)
self.last_states_for_each_channel = {'grayscale': None}
if self.perform_color_reconstruction:
self.crop_halfres = CropParameters(int(width / 2), int(height / 2),
self.model.num_encoders)
for channel in ['R', 'G', 'B', 'W']:
self.last_states_for_each_channel[channel] = None
self.event_preprocessor = EventPreprocessor(options)
self.intensity_rescaler = IntensityRescaler(options)
self.image_filter = ImageFilter(options)
self.unsharp_mask_filter = UnsharpMaskFilter(options, device=self.device)
self.image_writer = ImageWriter(options)
self.image_display = ImageDisplay(options)
def update_reconstruction(self, event_tensor, event_tensor_id, stamp=None):
with torch.no_grad():
with CudaTimer('Reconstruction'):
with CudaTimer('NumPy (CPU) -> Tensor (GPU)'):
events = event_tensor.unsqueeze(dim=0)
events = events.to(self.device)
events = self.event_preprocessor(events)
# Resize tensor to [1 x C x crop_size x crop_size] by applying zero padding
events_for_each_channel = {'grayscale': self.crop.pad(events)}
reconstructions_for_each_channel = {}
if self.perform_color_reconstruction:
events_for_each_channel['R'] = self.crop_halfres.pad(events[:, :, 0::2, 0::2])
events_for_each_channel['G'] = self.crop_halfres.pad(events[:, :, 0::2, 1::2])
events_for_each_channel['W'] = self.crop_halfres.pad(events[:, :, 1::2, 0::2])
events_for_each_channel['B'] = self.crop_halfres.pad(events[:, :, 1::2, 1::2])
# Reconstruct new intensity image for each channel (grayscale + RGBW if color reconstruction is enabled)
for channel in events_for_each_channel.keys():
with CudaTimer('Inference'):
new_predicted_frame, states = self.model(events_for_each_channel[channel],
self.last_states_for_each_channel[channel])
if self.no_recurrent:
self.last_states_for_each_channel[channel] = None
else:
self.last_states_for_each_channel[channel] = states
# Output reconstructed image
crop = self.crop if channel == 'grayscale' else self.crop_halfres
# Unsharp mask (on GPU)
new_predicted_frame = self.unsharp_mask_filter(new_predicted_frame)
# Intensity rescaler (on GPU)
new_predicted_frame = self.intensity_rescaler(new_predicted_frame)
with CudaTimer('Tensor (GPU) -> NumPy (CPU)'):
reconstructions_for_each_channel[channel] = new_predicted_frame[0, 0, crop.iy0:crop.iy1,
crop.ix0:crop.ix1].cpu().numpy()
if self.perform_color_reconstruction:
out = merge_channels_into_color_image(reconstructions_for_each_channel)
else:
out = reconstructions_for_each_channel['grayscale']
# Post-processing, e.g bilateral filter (on CPU)
out = self.image_filter(out)
self.image_writer(out, event_tensor_id, stamp, events=events)
self.image_display(out, events)
?
def __init__(self, options):
print('== Event preprocessing ==')
self.no_normalize = options.no_normalize
if self.no_normalize:
print('!!Will not normalize event tensors!!')
else:
print('Will normalize event tensors.')
self.hot_pixel_locations = []
if options.hot_pixels_file:
try:
self.hot_pixel_locations = np.loadtxt(options.hot_pixels_file, delimiter=',').astype(np.int)
print('Will remove {} hot pixels'.format(self.hot_pixel_locations.shape[0]))
except IOError:
print('WARNING: could not load hot pixels file: {}'.format(options.hot_pixels_file))
self.flip = options.flip
if self.flip:
print('Will flip event tensors.')
def __call__(self, events):
# Remove (i.e. zero out) the hot pixels
for x, y in self.hot_pixel_locations:
events[:, :, y, x] = 0
# Flip tensor vertically and horizontally
if self.flip:
events = torch.flip(events, dims=[2, 3])
# Normalize the event tensor (voxel grid) so that
# the mean and stddev of the nonzero values in the tensor are equal to (0.0, 1.0)
if not self.no_normalize:
with CudaTimer('Normalization'):
nonzero_ev = (events != 0)
num_nonzeros = nonzero_ev.sum()
if num_nonzeros > 0:
# compute mean and stddev of the **nonzero** elements of the event tensor
# we do not use PyTorch's default mean() and std() functions since it's faster
# to compute it by hand than applying those funcs to a masked array
mean = events.sum() / num_nonzeros
stddev = torch.sqrt((events ** 2).sum() / num_nonzeros - mean ** 2)
mask = nonzero_ev.float()
events = mask * (events - mean) / stddev
return events
class IntensityRescaler:
"""
Utility class to rescale image intensities to the range [0, 1],
using (robust) min/max normalization.
Optionally, the min/max bounds can be smoothed over a sliding window to avoid jitter.
"""
code
def __init__(self, options):
self.auto_hdr = options.auto_hdr
self.intensity_bounds = deque()
self.auto_hdr_median_filter_size = options.auto_hdr_median_filter_size
self.Imin = options.Imin
self.Imax = options.Imax
def __call__(self, img):
"""
param img: [1 x 1 x H x W] Tensor taking values in [0, 1]
"""
if self.auto_hdr:
with CudaTimer('Compute Imin/Imax (auto HDR)'):
Imin = torch.min(img).item()
Imax = torch.max(img).item()
# ensure that the range is at least 0.1
Imin = np.clip(Imin, 0.0, 0.45)
Imax = np.clip(Imax, 0.55, 1.0)
# adjust image dynamic range (i.e. its contrast)
if len(self.intensity_bounds) > self.auto_hdr_median_filter_size:
self.intensity_bounds.popleft()
self.intensity_bounds.append((Imin, Imax))
self.Imin = np.median([rmin for rmin, rmax in self.intensity_bounds])
self.Imax = np.median([rmax for rmin, rmax in self.intensity_bounds])
with CudaTimer('Intensity rescaling'):
img = 255.0 * (img - self.Imin) / (self.Imax - self.Imin)
img.clamp_(0.0, 255.0)
img = img.byte() # convert to 8-bit tensor
return img
class ImageWriter:
"""
Utility class to write images to disk.
Also writes the image timestamps into a text file.
"""
code
def __init__(self, options):
self.output_folder = options.output_folder
self.dataset_name = options.dataset_name
self.save_events = options.show_events
self.event_display_mode = options.event_display_mode
self.num_bins_to_show = options.num_bins_to_show
print('== Image Writer ==')
if self.output_folder:
ensure_dir(self.output_folder)
ensure_dir(join(self.output_folder, self.dataset_name))
print('Will write images to: {}'.format(join(self.output_folder, self.dataset_name)))
self.timestamps_file = open(join(self.output_folder, self.dataset_name, 'timestamps.txt'), 'a')
if self.save_events:
self.event_previews_folder = join(self.output_folder, self.dataset_name, 'events')
ensure_dir(self.event_previews_folder)
print('Will write event previews to: {}'.format(self.event_previews_folder))
atexit.register(self.__cleanup__)
else:
print('Will not write images to disk.')
def __call__(self, img, event_tensor_id, stamp=None, events=None):
if not self.output_folder:
return
if self.save_events and events is not None:
event_preview = make_event_preview(events, mode=self.event_display_mode,
num_bins_to_show=self.num_bins_to_show)
cv2.imwrite(join(self.event_previews_folder,
'events_{:010d}.png'.format(event_tensor_id)), event_preview)
cv2.imwrite(join(self.output_folder, self.dataset_name,
'frame_{:010d}.png'.format(event_tensor_id)), img)
if stamp is not None:
self.timestamps_file.write('{:.18f}\n'.format(stamp))
def __cleanup__(self):
if self.output_folder:
self.timestamps_file.close()
class ImageDisplay:
"""
Utility class to display image reconstructions
"""
code
def __init__(self, options):
self.display = options.display
self.show_events = options.show_events
self.color = options.color
self.event_display_mode = options.event_display_mode
self.num_bins_to_show = options.num_bins_to_show
self.window_name = 'Reconstruction'
if self.show_events:
self.window_name = 'Events | ' + self.window_name
if self.display:
cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
self.border = options.display_border_crop
self.wait_time = options.display_wait_time
def crop_outer_border(self, img, border):
if self.border == 0:
return img
else:
return img[border:-border, border:-border]
def __call__(self, img, events=None):
if not self.display:
return
img = self.crop_outer_border(img, self.border)
if self.show_events:
assert(events is not None)
event_preview = make_event_preview(events, mode=self.event_display_mode,
num_bins_to_show=self.num_bins_to_show)
event_preview = self.crop_outer_border(event_preview, self.border)
if self.show_events:
img_is_color = (len(img.shape) == 3)
preview_is_color = (len(event_preview.shape) == 3)
if(preview_is_color and not img_is_color):
img = np.dstack([img] * 3)
elif(img_is_color and not preview_is_color):
event_preview = np.dstack([event_preview] * 3)
img = np.hstack([event_preview, img])
cv2.imshow(self.window_name, img)
cv2.waitKey(self.wait_time)
class UnsharpMaskFilter:
"""
Utility class to perform unsharp mask filtering on reconstructed images.
"""
def optimal_crop_size(max_size, max_subsample_factor):
""" Find the optimal crop size for a given max_size and subsample_factor.
The optimal crop size is the smallest integer which is greater or equal than max_size,
while being divisible by 2^max_subsample_factor.
"""
crop_size = int(pow(2, max_subsample_factor) * ceil(max_size / pow(2, max_subsample_factor)))
return crop_size
class CropParameters:
""" Helper class to compute and store useful parameters for pre-processing and post-processing
of images in and out of E2VID.
Pre-processing: finding the best image size for the network, and padding the input image with zeros
Post-processing: Crop the output image back to the original image size
"""
def shift_image(X, dx, dy):
X = np.roll(X, dy, axis=0)
X = np.roll(X, dx, axis=1)
if dy > 0:
X[:dy, :] = np.expand_dims(X[dy, :], axis=0)
elif dy < 0:
X[dy:, :] = np.expand_dims(X[dy, :], axis=0)
if dx > 0:
X[:, :dx] = np.expand_dims(X[:, dx], axis=1)
elif dx < 0:
X[:, dx:] = np.expand_dims(X[:, dx], axis=1)
return X
def upsample_color_image(grayscale_highres, color_lowres_bgr, colorspace='LAB'):
"""
Generate a high res color image from a high res grayscale image, and a low res color image,
using the trick described in:
http://www.planetary.org/blogs/emily-lakdawalla/2013/04231204-image-processing-colorizing-images.html
"""
assert(len(grayscale_highres.shape) == 2)
assert(len(color_lowres_bgr.shape) == 3 and color_lowres_bgr.shape[2] == 3)
code
if colorspace == 'LAB':
# convert color image to LAB space
lab = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2LAB)
# replace lightness channel with the highres image
lab[:, :, 0] = grayscale_highres
# convert back to BGR
color_highres_bgr = cv2.cvtColor(src=lab, code=cv2.COLOR_LAB2BGR)
elif colorspace == 'HSV':
# convert color image to HSV space
hsv = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2HSV)
# replace value channel with the highres image
hsv[:, :, 2] = grayscale_highres
# convert back to BGR
color_highres_bgr = cv2.cvtColor(src=hsv, code=cv2.COLOR_HSV2BGR)
elif colorspace == 'HLS':
# convert color image to HLS space
hls = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2HLS)
# replace lightness channel with the highres image
hls[:, :, 1] = grayscale_highres
# convert back to BGR
color_highres_bgr = cv2.cvtColor(src=hls, code=cv2.COLOR_HLS2BGR)
return color_highres_bgr
def merge_channels_into_color_image(channels):
"""
Combine a full resolution grayscale reconstruction and four color channels at half resolution
into a color image at full resolution.
code
:param channels: dictionary containing the four color reconstructions (at quarter resolution),
and the full resolution grayscale reconstruction.
:return a color image at full resolution
"""
with Timer('Merge color channels'):
assert('R' in channels)
assert('G' in channels)
assert('W' in channels)
assert('B' in channels)
assert('grayscale' in channels)
# upsample each channel independently
for channel in ['R', 'G', 'W', 'B']:
channels[channel] = cv2.resize(channels[channel], dsize=None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
# Shift the channels so that they all have the same origin
channels['B'] = shift_image(channels['B'], dx=1, dy=1)
channels['G'] = shift_image(channels['G'], dx=1, dy=0)
channels['W'] = shift_image(channels['W'], dx=0, dy=1)
# reconstruct the color image at half the resolution using the reconstructed channels RGBW
reconstruction_bgr = np.dstack([channels['B'],
cv2.addWeighted(src1=channels['G'], alpha=0.5,
src2=channels['W'], beta=0.5,
gamma=0.0, dtype=cv2.CV_8U),
channels['R']])
reconstruction_grayscale = channels['grayscale']
# combine the full res grayscale resolution with the low res to get a full res color image
upsampled_img = upsample_color_image(reconstruction_grayscale, reconstruction_bgr)
return upsampled_img
return upsampled_img
def events_to_voxel_grid(events, num_bins, width, height):
"""
Build a voxel grid with bilinear interpolation in the time domain from a set of events.
code
:param events: a [N x 4] NumPy array containing one event per row in the form: [timestamp, x, y, polarity]
:param num_bins: number of bins in the temporal axis of the voxel grid
:param width, height: dimensions of the voxel grid
"""
assert(events.shape[1] == 4)
assert(num_bins > 0)
assert(width > 0)
assert(height > 0)
voxel_grid = np.zeros((num_bins, height, width), np.float32).ravel()
# normalize the event timestamps so that they lie between 0 and num_bins
last_stamp = events[-1, 0]
first_stamp = events[0, 0]
deltaT = last_stamp - first_stamp
if deltaT == 0:
deltaT = 1.0
events[:, 0] = (num_bins - 1) * (events[:, 0] - first_stamp) / deltaT
ts = events[:, 0]
xs = events[:, 1].astype(np.int)
ys = events[:, 2].astype(np.int)
pols = events[:, 3]
pols[pols == 0] = -1 # polarity should be +1 / -1
tis = ts.astype(np.int)
dts = ts - tis
vals_left = pols * (1.0 - dts)
vals_right = pols * dts
valid_indices = tis < num_bins
np.add.at(voxel_grid, xs[valid_indices] + ys[valid_indices] * width
+ tis[valid_indices] * width * height, vals_left[valid_indices])
valid_indices = (tis + 1) < num_bins
np.add.at(voxel_grid, xs[valid_indices] + ys[valid_indices] * width
+ (tis[valid_indices] + 1) * width * height, vals_right[valid_indices])
voxel_grid = np.reshape(voxel_grid, (num_bins, height, width))
return voxel_grid