Using Pillow (which works with Python 3.X as well as Python 2.7+), you can do the following:
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
Now you have all pixel values. If it is RGB or another mode can be read by im.mode
. Then you can get pixel (x, y)
by:
pixel_values[width*y+x]
Alternatively, you can use Numpy and reshape the array:
>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18 18 12]
A complete, simple to use solution is
# Third party modules
import numpy
from PIL import Image
def get_image(image_path):
"""Get a numpy array of an image so that one can access values[x][y]."""
image = Image.open(image_path, "r")
width, height = image.size
pixel_values = list(image.getdata())
if image.mode == "RGB":
channels = 3
elif image.mode == "L":
channels = 1
else:
print("Unknown mode: %s" % image.mode)
return None
pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
return pixel_values
image = get_image("gradient.png")
print(image[0])
print(image.shape)
Smoke testing the code
You might be uncertain about the order of width / height / channel. For this reason I've created this gradient:
The image has a width of 100px and a height of 26px. It has a color gradient going from #ffaa00
(yellow) to #ffffff
(white). The output is:
[[255 172 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 4]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 5]]
(100, 26, 3)
Things to note:
- The shape is (width, height, channels)
- The
image[0]
, hence the first row, has 26 triples of the same color