PixelAccess Class

The PixelAccess class provides read and write access toPIL.Image data at a pixel level.

Note

Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API.

Example

The following script loads an image, accesses one pixel from it, thenchanges it.

  1. from PIL import Image
  2. with Image.open('hopper.jpg') as im:
  3. px = im.load()
  4. print (px[4,4])
  5. px[4,4] = (0,0,0)
  6. print (px[4,4])

Results in the following:

  1. (23, 24, 68)
  2. (0, 0, 0)

Access using negative indexes is also possible.

  1. px[-1,-1] = (0,0,0)
  2. print (px[-1,-1])

PixelAccess Class

  • class PixelAccess
    • setitem(self, xy, color):
    • Modifies the pixel at x,y. The color is given as a singlenumerical value for single band images, and a tuple formulti-band images

Parameters:

  1. - **xy** The pixel coordinate, given as (x, y).
  2. - **color** The pixel value according to its mode. e.g. tuple (r, g, b) for RGB mode)
  • getitem(self, xy):
    • Returns the pixel at x,y. The pixel is returned as a single
    • value for single band images or a tuple for multiple bandimages

param xy:The pixel coordinate, given as (x, y).returns:a pixel value for single band images, a tuple ofpixel values for multiband images.

  • putpixel(self, xy, color):
  • Modifies the pixel at x,y. The color is given as a singlenumerical value for single band images, and a tuple formulti-band images. In addition to this, RGB and RGBA tuplesare accepted for P images.

Parameters:

  1. - **xy** The pixel coordinate, given as (x, y).
  2. - **color** The pixel value according to its mode. e.g. tuple (r, g, b) for RGB mode)
  • getpixel(self, xy):
    • Returns the pixel at x,y. The pixel is returned as a single
    • value for single band images or a tuple for multiple bandimages

param xy:The pixel coordinate, given as (x, y).returns:a pixel value for single band images, a tuple ofpixel values for multiband images.