Exemple #1
0
    def __init__(self, path_to_event_file, duration_ms=50.0, start_index=0):
        print('Will use fixed duration event windows of size {:.2f} ms'.format(
            duration_ms))
        print('Output frame rate: {:.1f} Hz'.format(1000.0 / duration_ms))
        file_extension = splitext(path_to_event_file)[1]
        #assert(file_extension in ['.txt', '.zip'])
        #self.is_zip_file = (file_extension == '.zip')
        """
        if self.is_zip_file:  # '.zip'
            self.zip_file = zipfile.ZipFile(path_to_event_file)
            files_in_archive = self.zip_file.namelist()
            assert(len(files_in_archive) == 1)  # make sure there is only one text file in the archive
            self.event_file = self.zip_file.open(files_in_archive[0], 'r')
        else:
            self.event_file = open(path_to_event_file, 'r')

        # ignore header + the first start_index lines
        for i in range(1 + start_index):
            self.event_file.readline()
        """
        self.event_file = AedatFile(path_to_event_file)
        i = 0
        for e in self.event_file['events']:
            if i >= start_index:
                break
            i += 1
        self.last_stamp = None
        self.duration_s = duration_ms / 1000.0
Exemple #2
0
 def read_aedatfile(self, aedat_path):
     """
      Function:
          read_aedatfile
      Parameters:
        aedat_path: input the aedat path
      Returns:
        output 'aedat_file'
      """
     with AedatFile(aedat_path) as aedat_file:
         # list all the names of streams in the file
         print(aedat_file.names)
         return aedat_file
def transformaedat4(filename):

    with AedatFile(filename) as f:
        names = f.names
        print("the following streams are availible in the file", names)
        print("taking all")
        returnArrays = []
        for name in names:
            # events will be a named numpy array
            events = np.hstack([packet for packet in f[name].numpy()])

            # Access information of all events by type
            x, y, timestamps, polarities = events['x'], events['y'], events[
                'timestamp'], events['polarity']
            print(events.shape)
            print(events[0:3])
            returnArrays.append((name, events))
    return returnArrays
Exemple #4
0
 def __init__(self, path_to_event_file, num_events=10000, start_index=0):
     print('Will use fixed size event windows with {} events'.format(
         num_events))
     print('Output frame rate: variable')
     """
     self.iterator = pd.read_csv(path_to_event_file, delim_whitespace=True, header=None,
                                 names=['t', 'x', 'y', 'pol'],
                                 dtype={'t': np.float64, 'x': np.int16, 'y': np.int16, 'pol': np.int16},
                                 engine='c',
                                 skiprows=start_index + 1, chunksize=num_events, nrows=None, memory_map=True)
     """
     self.event_file = AedatFile(path_to_event_file)
     i = 0
     for e in self.event_file['events']:
         if i >= start_index:
             break
         i += 1
     self.num_events = num_events
Exemple #5
0
def transformaedat4(filename):

    with AedatFile(filename) as f:
        names = f.names
        print("the following streams are availible in the file", names)
        print("taking all")
        returnArrays = []

        for name in names:
            events = []
            print("now takeing: ", name)
            for e in f[name]:
                events.append([e.x, e.y, e.timestamp, e.polarity])

            rtarr = np.asarray(events)
            print(rtarr[0:3])
            print(rtarr.shape)

            returnArrays.append((name, rtarr))
    return returnArrays
Exemple #6
0
def nomniglot_load_events_from_aedat(aedat_file_path, csv_file_path):
    # each aedat has 20 samples so this will give a list of 20 samples
    # instead of just 1

    print(aedat_file_path)

    timestamp, polarity, x, y = [], [], [], []
    samples_per_character = 20
    lst = []

    # readout and store the information from the aedat file
    with AedatFile(aedat_file_path) as f:  # read aedat4
        for e in f['events']:
            timestamp.append(e.timestamp)
            polarity.append(e.polarity)
            x.append(e.x)
            y.append(e.y)

    # each aedat has 20 samples, deliniated by timestamps in the csv file
    start_end_timestamp = pandas.read_csv(csv_file_path).values

    for i in range(samples_per_character):
        start_index = timestamp.index(start_end_timestamp[i][1])
        end_index = timestamp.index(start_end_timestamp[i][2])
        tmp = np.column_stack([
            np.array(timestamp[start_index:end_index], dtype=np.uint32),
            np.array(polarity[start_index:end_index], dtype=np.uint8),
            np.array(x[start_index:end_index], dtype=np.uint16),
            np.array(y[start_index:end_index], dtype=np.uint16)
        ])

        print(tmp.size)
        if tmp.size != 0:
            lst.append(tmp)
        else:
            print("empty sample")

    return lst
Exemple #7
0
from dv import AedatFile
import numpy as np
import scipy.io as sio
import h5py

# Input File Location
file_path = 'D:\\Documents\\Summer Scholarship\\Event-Based-HDF5-Video-Renderer-master\\HDF5 Converter\\Uncooled Cam Dark Setting\\Cooled Cam Dark\\0 Degrees Ambient\\dvSave-2020_01_28_11_52_15.aedat4'

# An empty list for data to be stored later
events_x=[]
events_y=[]
events_p=[]
events_ts=[]

with AedatFile(file_path) as f:
    # list all the names of streams in the file
            print(f.names)
    
    # loop through the "events" stream
    for e in f['events']:
        # Check For polarity data, if true == 1, if false == -1
        if e.polarity == True:
            events_3=1
        else:
            events_3=-1
        # Save data from "events" stream to a list
        events_x.append(e.x)
        events_y.append(e.y)
        events_p.append(events_3)
        events_ts.append(e.timestamp)
    # Storing the first row of events_ts as a variable
Exemple #8
0
def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print('aedat4tomat.py -i <inputfile> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('aedat4tomat.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    print('Input file is "', inputfile)
    print('Output file is "', outputfile)

    #Define output struct
    out = Struct()
    out.data = Struct()
    out.data.polarity = Struct()
    out.data.frame = Struct()
    out.data.imu6 = Struct()

    #Events
    out.data.polarity.polarity = []
    out.data.polarity.timeStamp = []
    out.data.polarity.x = []
    out.data.polarity.y = []

    #Frames
    out.data.frame.samples = []
    out.data.frame.position = []
    out.data.frame.sizeAll = []
    out.data.frame.timeStamp = []
    out.data.frame.frameStart = []
    out.data.frame.frameEnd = []
    out.data.frame.expStart = []
    out.data.frame.expEnd = []

    #IMU
    out.data.imu6.accelX = []
    out.data.imu6.accelY = []
    out.data.imu6.accelZ = []
    out.data.imu6.gyroX = []
    out.data.imu6.gyroY = []
    out.data.imu6.gyroZ = []
    out.data.imu6.temperature = []
    out.data.imu6.timeStamp = []

    data = {'aedat': out}

    with AedatFile(inputfile) as f:

        # loop through the "events" stream
        for e in f['events']:
            out.data.polarity.timeStamp.append(e.timestamp)
            out.data.polarity.polarity.append(e.polarity)
            out.data.polarity.x.append(e.x)
            out.data.polarity.y.append(e.y)

        # loop through the "frames" stream
        for frame in f['frames']:
            out.data.frame.samples.append(frame.image)
            out.data.frame.position.append(frame.position)
            out.data.frame.sizeAll.append(frame.size)
            out.data.frame.timeStamp.append(frame.timestamp)
            out.data.frame.frameStart.append(frame.timestamp_start_of_frame)
            out.data.frame.frameEnd.append(frame.timestamp_end_of_frame)
            out.data.frame.expStart.append(frame.timestamp_start_of_exposure)
            out.data.frame.expEnd.append(frame.timestamp_end_of_exposure)

        # loop through the "imu" stream
        for i in f['imu']:
            a = i.accelerometer
            g = i.gyroscope
            m = i.magnetometer
            out.data.imu6.accelX.append(a[0])
            out.data.imu6.accelY.append(a[1])
            out.data.imu6.accelZ.append(a[2])
            out.data.imu6.gyroX.append(g[0])
            out.data.imu6.gyroY.append(g[1])
            out.data.imu6.gyroZ.append(g[2])
            out.data.imu6.temperature.append(i.temperature)
            out.data.imu6.timeStamp.append(i.timestamp)

    #Permute images via numpy
    tmp = np.transpose(np.squeeze(np.array(out.data.frame.samples)), (1, 2, 0))
    out.data.frame.numDiffImages = tmp.shape[2]
    out.data.frame.size = out.data.frame.sizeAll[0]
    out.data.frame.samples = tmp.tolist()

    #Add counts
    out.data.polarity.numEvents = len(out.data.polarity.x)
    out.data.imu6.numEvents = len(out.data.imu6.accelX)
    sio.savemat(outputfile, data)
Exemple #9
0
class FixedDurationEventReader:
    """
    Reads events from a '.txt' or '.zip' file, and packages the events into
    non-overlapping event windows, each of a fixed duration.

    **Note**: This reader is much slower than the FixedSizeEventReader.
              The reason is that the latter can use Pandas' very efficient cunk-based reading scheme implemented in C.
    """
    def __init__(self, path_to_event_file, duration_ms=50.0, start_index=0):
        print('Will use fixed duration event windows of size {:.2f} ms'.format(
            duration_ms))
        print('Output frame rate: {:.1f} Hz'.format(1000.0 / duration_ms))
        file_extension = splitext(path_to_event_file)[1]
        #assert(file_extension in ['.txt', '.zip'])
        #self.is_zip_file = (file_extension == '.zip')
        """
        if self.is_zip_file:  # '.zip'
            self.zip_file = zipfile.ZipFile(path_to_event_file)
            files_in_archive = self.zip_file.namelist()
            assert(len(files_in_archive) == 1)  # make sure there is only one text file in the archive
            self.event_file = self.zip_file.open(files_in_archive[0], 'r')
        else:
            self.event_file = open(path_to_event_file, 'r')

        # ignore header + the first start_index lines
        for i in range(1 + start_index):
            self.event_file.readline()
        """
        self.event_file = AedatFile(path_to_event_file)
        i = 0
        for e in self.event_file['events']:
            if i >= start_index:
                break
            i += 1
        self.last_stamp = None
        self.duration_s = duration_ms / 1000.0

    def __iter__(self):
        return self

    def __del__(self):
        if self.is_zip_file:
            self.zip_file.close()

        self.event_file.close()

    def __next__(self):
        with Timer('Reading event window from file'):
            event_list = []
            for e in self.event_file['events']:
                #if self.is_zip_file:
                #    line = line.decode("utf-8")
                #t, x, y, pol = line.split(' ')
                #t, x, y, pol = float(t), int(x), int(y), int(pol)
                t, x, y, pol = float(e.timestamp) * 1e-6, int(e.x), int(
                    e.y), int(e.polarity)
                event_list.append([t, x, y, pol])
                if self.last_stamp is None:
                    self.last_stamp = t
                if t > self.last_stamp + self.duration_s:
                    self.last_stamp = t
                    event_window = np.array(event_list)
                    return event_window

        raise StopIteration
                        action='store_true')
    parser.set_defaults(compute_voxel_grid_on_cpu=False)

    set_inference_options(parser)

    args = parser.parse_args()

    # Read sensor size from the first first line of the event file
    path_to_events = args.input_file
    """
    header = pd.read_csv(path_to_events, delim_whitespace=True, header=None, names=['width', 'height'],
                         dtype={'width': np.int, 'height': np.int},
                         nrows=1)
    width, height = header.values[0]
    """
    with AedatFile(path_to_events) as header:
        height, width = header['events'].size
    print('Sensor size: {} x {}'.format(width, height))

    # Load model
    model = load_model(args.path_to_model)
    device = get_device(args.use_gpu)

    model = model.to(device)
    model.eval()

    reconstructor = ImageReconstructor(model, height, width, model.num_bins,
                                       args)
    """ Read chunks of events using Pandas """

    # Loop through the events and reconstruct images
Exemple #11
0
import numpy as np
import imageio

def main(argv):
    inputfile = ''
    outputfile = ''
    opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    for opt, arg in opts:
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg    

    data = {'aedat': out}

    with AedatFile(inputfile) as f:
        
        fps = 30.0
        dt = 1/(fps/1000.0)
        I = np.zeros((240,320))
        prev_time = 0
        initial_time = 1588242864305911 #modify the value
        for e in f['events']:
            time = (e.timestamp - initial_time)//1000
            time = int(time//dt)
            x = e.x
            y = e.y
            if(prev_time != time):
                imageio.imwrite('images/'+str(prev_time)+'.png', I)
                I = np.zeros((240,320))
            I[y][x] = 255.0