1

I want to create a 2d numpy array of all the pixel locations for a 512 x 512 image. Meaning there would be 5122 or 262,144 values. It may be slightly more if the x and y zeroes are considered, but you get the idea.

To do it manually would be like this pixels = np.array([[0, 1], [0, 2], [0,3], [0,4]]) all the way to the end. But obviously I need to automate it. The order of pixels doesn't matter though. It needs to be in that "format" so I can access the pixels x and y values by 0 and 1 index i.e. pixels[0][0] for the first pixel's x value and pixels[0][1] for the first pixel's y value.

1
  • simply use for-loops to automate it. Commented Dec 2, 2021 at 6:40

2 Answers 2

3

Try this:

pixels = np.array([[x, y] for y in range(512) for x in range(512)])

Note that you can modify it for different x or y values.

Sign up to request clarification or add additional context in comments.

Comments

1

numpy is openly used to process and manipulate images through multi-dimensional arrays, since they are very useful to storing values as pixels (rgb, rgba, greyscale, etc ...)

 RGB:

>>> import numpy as np
>>> from PIL import Image
>>> array = np.zeros([100, 200, 3], dtype=np.uint8)
>>> array[:,:100] = [255, 128, 0] #Orange left side
>>> array[:,100:] = [0, 0, 255]   #Blue right side
>>> img = Image.fromarray(array)
>>> array[:,:100] = [100, 128, 0]
>>> array[:,100:] = [0, 0, 200]
>>> img = Image.fromarray(array)
>>> img.save('img.png')

im1

 GREYSCALE:

>>> import numpy as np
>>> from PIL import Image
>>> array = np.zeros([100, 200], dtype=np.uint8)
>>> # Set grey value to black or white depending on x position
>>> for x in range(200):
>>>     for y in range(100):
>>>         if (x % 16) // 8 == (y % 16) // 8:
>>>             array[y, x] = 0
>>>         else:
>>>             array[y, x] = 255
>>>
>>> img = Image.fromarray(array)
>>> img.save('img.png')

im2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.