简体   繁体   中英

array of image pixels and their color

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM