import numpy as np def to_sparse(data, th = 0): """ Convert frames stack ndarray[frame, row, col] to sparse array. Warning: this function drops the frame numbers and only keeps row, col, energy """ sparse_dt = [('row', np.int16), ('col', np.int16), ('energy', data.dtype)] size = (data>th).sum() sparse = np.zeros(size, sparse_dt) frames, rows, cols = np.where(data>th) for i,(f,r,c) in enumerate(zip(frames, rows, cols)): sparse[i] = (r, c, data[f,r,c]) return sparse