import os import numpy as np from matplotlib import pyplot as plt
事件数据提取
# Simple codre. There may be more efficient ways. defextract_data(filename): infile = open(filename, 'r') timestamp = [] x = [] y = [] pol = [] for line in infile: words = line.split() timestamp.append(float(words[0])) x.append(int(words[1])) y.append(int(words[2])) pol.append(int(words[3])) infile.close() return timestamp,x,y,pol
filename_sub = 'slider_depth/events_chunk.txt' # Call the function to read data timestamp, x, y, pol = extract_data(filename_sub)
# Same plot as above, but changing the color map fig = plt.figure() fig.suptitle('Balance of event polarities') maxabsval = np.amax(np.abs(img)) plt.imshow(img, cmap='seismic_r', clim=(-maxabsval,maxabsval)) plt.xlabel("x [pixels]") plt.ylabel("y [pixels]") plt.colorbar() plt.show()
# Time Surface (or time map, or SAE="Surface of Active Events") num_event = len(timestamp) print("Time surface: numevents = ", num_event)
sae_pos = np.zeros(img_size, np.float32) sae_neg = np.zeros(img_size, np.float32) time_ref = timestamp[-1] # time of the last event in the packet tau = 0.03# decay parameter (in seconds) depends on motion of the scene
# Time Surface (or time map, or SAE="Surface of Active Events") num_event = len(timestamp) print("Time surface: numevents = ", num_event)
img = np.zeros(img_size, np.float32) time_ref = timestamp[-1] # time of the last event in the packet tau = 0.03# decay parameter (in seconds) depends on motion of the scene
for each_event inrange (num_event): img[y[each_event], x[each_event]] = np.exp(-(time_ref - timestamp[each_event])/tau)
# Time Surface (or time map, or SAE="Surface of Active Events") num_event = len(timestamp) print("Time surface: numevents = ", num_event)
sae_pos = np.zeros(img_size, np.float32) sae_neg = np.zeros(img_size, np.float32) time_ref = timestamp[-1] # time of the last event in the packet tau = 0.03# decay parameter (in seconds) depends on motion of the scene
m = 2000# Number of points to plot print("Space-time plot and movie: numevents = ", m)
# Plot without polarity fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #ax.set_aspect('equal') # only works for time in Z axis ax.scatter(x[:m], timestamp[:m], y[:m], marker='.', c='b') ax.set_xlabel('x [pix]') ax.set_ylabel('time [s]') ax.set_zlabel('y [pix] ') ax.view_init(azim=-90, elev=-180) # Change viewpoint with the mouse, for example plt.show()
# %% Plot each polarity with a different color (red / blue) idx_pos = np.asarray(pol[:m]) > 0# the index of positive event idx_neg = np.logical_not(idx_pos) # the index of negative event xnp = np.asarray(x[:m]) ynp = np.asarray(y[:m]) tnp = np.asarray(timestamp[:m]) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xnp[idx_pos], tnp[idx_pos], ynp[idx_pos], marker='.', c='b') ax.scatter(xnp[idx_neg], tnp[idx_neg], ynp[idx_neg], marker='.', c='r') ax.set(xlabel='x [pix]', ylabel='time [s]', zlabel='y [pix]') ax.view_init(azim=-90, elev=-180) plt.show()
num_bins = 5 print("Number of time bins = ", num_bins)
t_max = np.amax(np.asarray(timestamp[:m])) t_min = np.amin(np.asarray(timestamp[:m])) t_range = t_max - t_min dt_bin = t_range / num_bins # size of the time bins (bins) t_edges = np.linspace(t_min,t_max,num_bins+1) # Boundaries of the bins
# Compute 3D histogram of events manually with a loop # ("Zero-th order or nearest neighbor voting") hist3d = np.zeros(img.shape+(num_bins,), np.int) for ii in xrange(m): idx_t = int( (timestamp[ii]-t_min) / dt_bin ) if idx_t >= num_bins: idx_t = num_bins-1# only one element (the last one) hist3d[y[ii],x[ii],idx_t] += 1
# Checks: print("hist3d") print(hist3d.shape) print(np.sum(hist3d)) # This should equal the number of votes
# %% Compute 3D histogram of events using numpy function histogramdd # https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogramdd.html#numpy.histogramdd
# Specify bin edges in each dimension bin_edges = (np.linspace(0,img_size[0],img_size[0]+1), np.linspace(0,img_size[1],img_size[1]+1), t_edges) yxt = np.transpose(np.array([y[:m], x[:m], timestamp[:m]])) hist3dd, edges = np.histogramdd(yxt, bins=bin_edges)
# Checks print("\nhist3dd") print("min = ", np.min(hist3dd)) print("max = ", np.max(hist3dd)) print (np.sum(hist3dd)) print (np.linalg.norm( hist3dd - hist3d)) # Check: zero if both histograms are equal 三维向量求范数 print("Ratio of occupied bins = ", np.sum(hist3dd > 0) / float(np.prod(hist3dd.shape)) )
# Plot of the 3D histogram. Empty cells are transparent (not displayed) # Example: https://matplotlib.org/3.1.1/gallery/mplot3d/voxels_rgb.html#sphx-glr-gallery-mplot3d-voxels-rgb-py
fig = plt.figure() fig.suptitle('3D histogram (voxel grid), zero-th order voting') ax = fig.gca(projection='3d') # prepare some coordinates r, g, b = np.indices((img_size[0]+1,img_size[1]+1,num_bins+1)) ax.voxels(g,b,r, hist3d) # No need to swap the data to plot with reordered axes ax.set(xlabel='x', ylabel='time bin', zlabel='y') ax.view_init(azim=-90, elev=-180) # edge-on, along time axis #ax.view_init(azim=-63, elev=-145) # oblique viewpoint plt.show()
下面是一些关于插值的表达方法,这里不作具体的解释了,仅仅贴一下代码吧
# %% Compute interpolated 3D histogram (voxel grid) hist3d_interp = np.zeros(img.shape+(num_bins,), np.float64) for ii in xrange(m-1): tn = (timestamp[ii] - t_min) / dt_bin # normalized time, in [0,num_bins] ti = np.floor(tn-0.5) # index of the left bin dt = (tn-0.5) - ti # delta fraction # Voting on two adjacent bins if ti >=0 : hist3d_interp[y[ii],x[ii],int(ti) ] += 1. - dt if ti < num_bins-1 : hist3d_interp[y[ii],x[ii],int(ti)+1] += dt
# Checks print("\nhist3d_interp") print("min = ", np.min(hist3d_interp)) print("max = ", np.max(hist3d_interp)) print np.sum(hist3d_interp) # Some votes are lost because of the missing last layer print np.linalg.norm( hist3d - hist3d_interp) print("Ratio of occupied bins = ", np.sum(hist3d_interp > 0) / float(np.prod(hist3d_interp.shape)) )
# %% A different visualization viewpoint ax.view_init(azim=-90, elev=-180) # edge-on, along time axis plt.show()
# %% Compute interpolated 3D histogram (voxel grid) using polarity hist3d_interp_pol = np.zeros(img.shape+(num_bins,), np.float64) for ii in xrange(m-1): tn = (timestamp[ii] - t_min) / dt_bin # normalized time, in [0,num_bins] ti = np.floor(tn-0.5) # index of the left bin dt = (tn-0.5) - ti # delta fraction # Voting on two adjacent bins if ti >=0 : hist3d_interp_pol[y[ii],x[ii],int(ti) ] += (1. - dt) * (2*pol[ii]-1) if ti < num_bins-1 : hist3d_interp_pol[y[ii],x[ii],int(ti)+1] += dt * (2*pol[ii]-1)
# Checks # Some votes are lost because of the missing last layer print("\nhist3d_interp_pol") print("min = ", np.min(hist3d_interp_pol)) print("max = ", np.max(hist3d_interp_pol)) print np.sum(np.abs(hist3d_interp_pol)) print("Ratio of occupied bins = ", np.sum(np.abs(hist3d_interp_pol) > 0) / float(np.prod(hist3d_interp_pol.shape)) )
# Plot interpolated voxel grid using polarity # Normalize the symmetric range to [0,1] maxabsval = np.amax(np.abs(hist3d_interp_pol)) colors = np.zeros(hist3d_interp_pol.shape + (3,)) tmp = (hist3d_interp_pol + maxabsval)/(2*maxabsval) colors[..., 0] = tmp colors[..., 1] = tmp colors[..., 2] = tmp