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.
CodePudding user response:
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.
CodePudding user response:
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 ...)
example (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')
example (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')