Skip to content

Instantly share code, notes, and snippets.

@tavin
Created June 1, 2018 12:25
Show Gist options
  • Save tavin/17310669040c1268775d2911924bbee1 to your computer and use it in GitHub Desktop.
Save tavin/17310669040c1268775d2911924bbee1 to your computer and use it in GitHub Desktop.
count the longest line of consecutive True along an axis
def consecutive(cond, axis):
cond = np.moveaxis(cond, axis, -1)
measure = np.zeros(cond.shape[:-1], dtype=np.uint32)
diff = np.diff(cond)
for index in np.ndindex(measure.shape):
boundary = np.flatnonzero(diff[index])
if not len(boundary):
continue
if cond[index][0]:
boundary = np.insert(boundary, 0, -1)
if len(boundary) % 2:
boundary = np.append(boundary, len(diff[index]))
measure[index] = np.max(boundary[1::2] - boundary[0::2])
return measure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment