Home > database >  array of image pixels and their color
array of image pixels and their color

Time:06-15

I have a grayscale image, I would like to split it into pixels and determine the grayscale in each pixel of the image. The array is needed in the following form: (pixel by X, pixel by Y, gray shade 0-255).

1,1,25;

1,2,36;

1,3,50; . . .

50,60,96; . . . if the image is 500 by 600 dots, then at the end it should get - (500,600, grayscale).

Could you tell me please, how can I get such an array of data from an image? What do I need to do? Which libraries should I use? If there is someone who has solved such a problem, please give an example. Thank you very much!

CodePudding user response:

I would do this:

# random data
np.random.seed(10)
img = np.random.randint(0,256, (500,600))

# coordinates
# np.meshgrid is also a good (better) choice
x, y = np.where(np.ones_like(img))

# put them together
out = np.stack([x,y, img.ravel()], axis=1)

Output:

array([[  0,   0,   9],
       [  0,   1, 125],
       [  0,   2, 228],
       ...,
       [499, 597, 111],
       [499, 598, 128],
       [499, 599,   8]])

CodePudding user response:

If you already have an image file, you can read it like this:

from PIL import Image

img = Image.open('/path/to/image.png')

To get this an an array:

import numpy as np

ima = np.asarray(img)

If it's really an 8-bit greyscale image, you might be able to use Image.open('image.png', mode='L'), but in any case you can always just get the red channel with ima[:, :, 0]. If it's greyscale, all the channels will be equal.

Now you can stack these grey levels with the coordinates:

h, w, _ = ima.shape
x, y = np.meshgrid(np.arange(w), np.arange(h))
np.dstack([x, y, ima[..., 0]])
  • Related