Assume that we have a 2d-array (such as a depth image). I'm looking for an efficient way to serialize this array and apply a function.
arrayis aheightxwidth2d-array.- Serializing
array--> list of[x,y,array[y,x]]for all combinations ofxinrange(0,width)andyinrange(0,height). - Applying a function
func:func(x,y,array[y,x])
Example code:
import numpy as np
import itertools
width,height= 640,480
xstep,ystep= 1,1
array= np.array([np.sqrt(x*x+y*y) for y,x in itertools.product(range(0,height,ystep), range(0,width,xstep))]).reshape(height,width)
func= lambda x,y,z: [np.sqrt(x),np.sqrt(y),np.sqrt(x*x+y*y+z*z)]
I tried several approaches:
%%time
points1= [func(x,y,array[y,x]) for y,x in itertools.product(range(0,height,ystep), range(0,width,xstep))]
#--> Wall time: 1.15 s
%%time
points2= [func(x,y,array[y,x]) for y,x in itertools.product(np.arange(0,height,ystep), np.arange(0,width,xstep))]
#--> Wall time: 2.09 s
%%time
points3= [func(x,y,array[y,x]) for y,x in np.array(np.meshgrid(range(0,height,ystep),range(0,width,xstep))).T.reshape(-1,2)]
#--> Wall time: 2.16 s
points1==points2, points1==points3
#--> (True, True)
Is there a faster solution than these?
numpy.ndenumerate. It is an alternative forenumeratein numpynumpy.ndenumerateruns a bit slower actually, as well asnumpy.ndindex