I am trying to perform inverse warping given a homography matrix, and to do that efficiently I need a numpy array that looks like this:
([[0, 0, 1], [0, 1, 1], [0, 2, 1], ... [1, 0, 1], [1, 1, 1], ... [n, p, 1]])
Where n is an image's width (im.shape[0]
) and p is the image's height (im.shape[1]
). Any idea on how to efficiently construct numpy arrays that look like that?
Edit:
There is some discussion on which is the fastest, if anyone has any info on that I think it'd be interesting to hear. I appreciate everyone's help!
Using indices_merged_arr_generic_using_cp
by @unutbu -
def indices_one_grid(n,p):
ar = np.ones((n,p),dtype=int)
return indices_merged_arr_generic_using_cp(ar)
Sample run -
In [141]: indices_one_grid(n=3,p=4)
Out[141]:
array([[0, 0, 1],
[0, 1, 1],
[0, 2, 1],
[0, 3, 1],
[1, 0, 1],
[1, 1, 1],
[1, 2, 1],
[1, 3, 1],
[2, 0, 1],
[2, 1, 1],
[2, 2, 1],
[2, 3, 1]])
Other approaches -
def MSeifert(n,p):
x, y = np.mgrid[:n, :p]
return np.stack([x.ravel(), y.ravel(), np.ones(x.size, dtype=int)], axis=1)
def DanielF(n,p):
return np.vstack([np.indices((n,p)), np.ones((1, n,p))]).reshape(3,-1).T
def Aaron(n,p):
arr = np.empty([n*p,3])
arr[:,0] = np.repeat(np.arange(n),p)
arr[:,1] = np.tile(np.arange(p),n)
arr[:,2] = 1
return arr
Timings -
In [152]: n=1000;p=1000
In [153]: %timeit MSeifert(n,p)
...: %timeit DanielF(n,p)
...: %timeit Aaron(n,p)
...: %timeit indices_one_grid(n,p)
...:
100 loops, best of 3: 15.8 ms per loop
100 loops, best of 3: 8.46 ms per loop
100 loops, best of 3: 10.4 ms per loop
100 loops, best of 3: 4.78 ms per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With