Pillow - Set Pixel Value
Pillow - Get pixel value at a position in image
We can set the pixel value in an image at specified coordinates in Pillow, by calling Image.putpixel() function on the given image and passing the pixel coordinates tuple and pixel value as arguments.
Syntax of putpixel() function
The syntax of putpixel() function from PIL.Image module is
PIL.Image.putpixel(xy, value)
where
Parameter | Description |
---|---|
xy | The coordinate, given as (x, y). |
value | The pixel value. If image is multi-channel, then it is a tuple, where each value in tuple represents value for the respective channel. |
Examples
1. Set pixel at (50, 100) to while color, in image
In the following example, we read an image test_image.jpg
into an Image object. Then, we set the pixel at (50, 100)
with a pixel value of (255, 255, 255) using Image.putpixel() function.
We save the resulting image to a file resulting_image.jpg
.
Python Program
from PIL import Image
# Open the image
image = Image.open("test_image.jpg")
# (x, y) position
xy = (50, 100)
# Pixel value
value = (255, 255, 255)
# Set pixel value
image.putpixel(xy, value)
image.save("resulting_image.jpg")
Original Image [test_image.jpg]
Output Image [resulting_image.jpg]
You can notice a white pixel on the top left corner, at (50, 100) position. Because a pixel value of (255, 255, 255) represents white color.
Summary
In this Python Pillow Tutorial, we learned how to set the pixel at an XY position in the image with a specific pixel value using PIL.Image.putpixel() function, with the help of examples.