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.
The following script loads an image, accesses one pixel from it, then changes it.
from PIL import Image with Image.open("hopper.jpg") as im: px = im.load() print(px[4, 4]) px[4, 4] = (0, 0, 0) print(px[4, 4])
Results in the following:
(23, 24, 68) (0, 0, 0)
Access using negative indexes is also possible.
px[-1, -1] = (0, 0, 0) print(px[-1, -1])
- class PIL.PyAccess.PyAccess¶
Returns the pixel at x,y. The pixel is returned as a single value for single band images or a tuple for multiple band images
xy – The pixel coordinate, given as (x, y). See Coordinate System.
a pixel value for single band images, a tuple of pixel values for multiband images.