np.apply_along_axis third dimension python code example
Example 1: np.apply_along_axis third dimension python
In [131]: A = np.random.randint(0,255,(512,512,3)) # 512x512 colored image
In [132]: def org_app(A):
...: out = np.zeros(A.shape)
...: for i in range(A.shape[0]):
...: for j in range(A.shape[1]):
...: out[i,j] = chromaticity(A[i,j])
...: return out
...:
In [133]: %timeit org_app(A)
1 loop, best of 3: 5.99 s per loop
In [134]: %timeit np.apply_along_axis(chromaticity, 2, A) #@hpaulj's soln
1 loop, best of 3: 9.68 s per loop
In [135]: %timeit np.log(A/np.power(np.sum(A,2,keepdims=True),1/3))
10 loops, best of 3: 90.8 ms per loop
Example 2: numpy apply function to array
import numpy as np
arr = np.array([1,2,3,4])
print(np.apply_along_axis(lambda x : x ** 2, 0, arr))
#Output: array([ 1, 4, 9, 16])