Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest method to create 2D numpy array whose elements are in range

Tags:

range

numpy

I want to create a 2D numpy array where I want to store the coordinates of the pixels such that numpy array looks like this

[(0, 0), (0, 1), (0, 2), ...., (0, 510), (0, 511)
 (1, 0), (1, 1), (1, 2), ...., (1, 510), (1, 511)
 ..
 ..
 ..
 (511, 0), (511, 1), (511, 2), ...., (511, 510), (511, 511)]

This is a ridiculous question but I couldn't find anything yet.

like image 903
Froyo Avatar asked Aug 21 '13 14:08

Froyo


People also ask

How do you make a 2D NumPy array?

To create a NumPy array, you can use the function np. array() . All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list.

Which method takes 2 dimensional data in Python?

In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.

What is the NumPy function used to create evenly spaced arrays analogous to the range () function used in Python?

arange() NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it.

How do you extract all numbers between a given range from a NumPy array?

Using the logical_and() method The logical_and() method from the numpy package accepts multiple conditions or expressions as a parameter. Each of the conditions or the expressions should return a boolean value. These boolean values are used to extract the required elements from the array.


1 Answers

Can use np.indices or np.meshgrid for more advanced indexing:

>>> data=np.indices((512,512)).swapaxes(0,2).swapaxes(0,1)
>>> data.shape
(512, 512, 2)

>>> data[5,0]
array([5, 0])
>>> data[5,25]
array([ 5, 25])

This may look odd because its really made to do something like this:

>>> a=np.ones((3,3))
>>> ind=np.indices((2,1))
>>> a[ind[0],ind[1]]=0
>>> a
array([[ 0.,  1.,  1.],
       [ 0.,  1.,  1.],
       [ 1.,  1.,  1.]])

A mgrid example:

np.mgrid[0:512,0:512].swapaxes(0,2).swapaxes(0,1)

A meshgrid example:

>>> a=np.arange(0,512)
>>> x,y=np.meshgrid(a,a)
>>> ind=np.dstack((y,x))
>>> ind.shape
(512, 512, 2)

>>> ind[5,0]
array([5, 0])

All are equivalent ways of doing this; however, meshgrid can be used to create non-uniform grids.

If you do not mind switching row/column indices you can drop the final swapaxes(0,1).

like image 55
Daniel Avatar answered Oct 24 '22 06:10

Daniel