VikkyB
VikkyB

Reputation: 1450

Import RGB value of each pixel in an image to 1-D array

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.

Upvotes: 1

Views: 1330

Answers (2)

askewchan
askewchan

Reputation: 46578

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

Upvotes: 1

David Robinson
David Robinson

Reputation: 78630

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

Upvotes: 1

Related Questions