Last modified on 15 September 2010, at 20:29

Python Imaging Library/Editing Pixels

With PIL you can easily access and change the data stored in the pixels of an image. To get the pixel map, call load() on an image. The pixel data can then be retrieved by indexing the pixel map as an array.

pixelMap = img.load() #create the pixel map
pixel = pixelMap[0,0] #get the first pixel's value

When you change the pixel data, it is changed in the image it came from (since the pixel map is just a reference to the data rather than a copy).

ExampleEdit

Resultant image

The following snippet shows how to change the pixel values in an image based on the index of the pixel:

import Image
 
img = Image.new( 'RGB', (255,255), "black") # create a new black image
pixels = img.load() # create the pixel map
 
for i in range(img.size[0]):    # for every pixel:
    for j in range(img.size[1]):
        pixels[i,j] = (i, j, 100) # set the colour accordingly
 
img.show()