1

How to import RGB value of each pixel in an image to 1-D array?

I am using following thing:

from PIL import Image
im = Image.open("bride.jpg")
pix = im.load()
print pix[x,y]

this imports it into 2-D array which is not iterable. I want this same thing but in 1-D array.

VikkyB
  • 1,440
  • 4
  • 16
  • 26

2 Answers2

1

You can flatten the pixels into a 1D array as follows:

width, height = im.size
pixels = [pix[i, j] for i in range(width) for j in range(height)]
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • It is a good solution but it is messing up the order of original array. The 1-D array which I want should be something like(assuming i to be row numbers in 2-D array): row i then row i+1 right behind that ith row and so on. Just like how compiler goes. – VikkyB Mar 06 '13 at 04:37
  • @VikasBansal: I don't understand the order you want. Do you want `(0, 0), (0, 1), (0, 2)...(1, 0), (1, 1), (1, 2)...` or do you want `(0, 0), (1, 0), (2, 0)...(0, 1), (1, 1), (2, 1)...` – David Robinson Mar 06 '13 at 04:39
  • In that case, the above solution *should* give you the answer you want. Can you show an example of a case where it doesn't? – David Robinson Mar 06 '13 at 04:42
  • Lets say the number of rows and columns in original array were N. Now if you pull the value of last element in 2-D array that is pix[N-1,N-1], it is not the same value as in new 1-d array pixel[(N-1)*(N-1)]. – VikkyB Mar 06 '13 at 04:49
  • @VikasBansal: It should be the same. Are you sure that your image is a square image that is N by N? (Try running `pix[width - 1, height - 1] == pixels[-1]` after my code) – David Robinson Mar 06 '13 at 04:58
1

Easy if you're using numpy, and no need to load the image.

from PIL import Image
import numpy as np
im = Image.open("bride.jpg")

pix_flatiter = np.asarray(im).flat  # is an iterable

If you want to load the whole array, you can do:

pix_flat = np.asarray(im).flatten() # is an array
askewchan
  • 45,161
  • 17
  • 118
  • 134