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.
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.
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.
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.
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.
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)
.
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