Use the Python Imaging Library (PIL) to display pixel values. Open the image with Image.open('filename')
, then load pixels with pixels = image.load()
. Access individual pixel values using pixels[x, y]
.
Key takeaways:
Pixels are the smallest units of a digital image, defined by RGB color values.
Pixel-level control allows for precise image processing and analysis.
Use the Python Imaging Library (PIL) to manipulate images at a pixel level.
Open an image with
Image.open('filename')
and save it withimage.save('path')
.Access pixel data using
load()
, which returns a pixel-access object.Individual pixel colors are read as RGB tuples, e.g.,
pixels[x, y]
.Modify pixels by assigning new RGB values to specific coordinates, e.g.,
pixels[x, y] = (255, 0, 0)
for red.
Pixels, short for picture elements, are the smallest units of a digital image or display. They are fundamental to digital imaging and display technologies and form the building blocks of any digital picture or screen output. Each pixel represents a single point in the image and has a specific color value, typically defined by a combination of red, green, and blue (RGB) components. In color images, each pixel’s color is determined by the intensity levels of these three primary colors.
Pixel-level control and data access open up a world of possibilities in image processing, analysis, and creation, providing the tools for precise and innovative work across various fields. We can access and manipulate pixel-level data using the Python Imaging Library (PIL). This Answer uses the following image as a sample and guides through the basics of pixel-level image control with Pillow.
The image, named ed_sample.png
, is placed in the current working directory, so uploading it to the widget is unnecessary.
To begin working with an image, we need to open it.
from PIL import Imageimage = Image.open('ed_sample.png')print(image)
Code explanation:
Line 1: This line imports the Image
module from PIL. The Image
module contains functions and classes for opening, manipulating, and saving many different image file formats.
Line 3: This line uses the Image.open()
function from the Image
module to open an image file. The function takes a file path (in this case, we have saved 'ed_sample.png'
in our current working directory) as an argument and returns an Image
object.
Line 5: This line prints the string representation of the PIL Image
object. This object allows us to perform various operations, such as viewing, editing, and saving images.
Let’s also learn how to save an image file. The save
method of the Image
object allows you to save an image. Run the code given below and see if it outputs an image file:
To display an image in the widget, save it in the ./output/
directory.
from PIL import Imageimage = Image.open('ed_sample.png')image.save('./output/ed_sample.png')
Code explanation:
Line 5: This line uses the save()
method of the Image
object to save the image to a new file. In the file path provided, ./output
specifies a subdirectory in the current working directory.
Pillow allows us to access pixel data using the load
method, which returns a pixel access object. This object can be used to read and write individual pixel values.
from PIL import Imageimage = Image.open('ed_sample.png')pixels = image.load()print (pixels)
Explanation:
Line 5: We use the load()
method of the Image
object to load the image’s pixel data and save the output in the variable pixels
. The output is a pixel-access object that allows us to read and modify an image’s pixels.
We can now access individual pixels using their (x, y) coordinates. Each pixel comprises a three-value tuple (R, G, B), corresponding to the red, green, and blue components that the pixel comprises. Each component can attain a maximum value of 255
and a minimum value of 0
.
from PIL import Imageimage = Image.open('ed_sample.png')pixels = image.load()pixel_value = pixels[100, 100]print(pixel_value) # Output will be a tuple, e.g., (R, G, B)
Code explanation:
Line 7: In this line, we access the pixel’s value at coordinates (100, 100) using the pixels
object and assign this value to the variable pixel_value
.
If you want to know how to get the list of colors in an image using PIL, visit our Answer on How to get the list of colors in an image in Python.
We can simply assign a new value to the desired coordinates to modify a pixel. For instance, to change the pixel at (100, 100)
to red, the code will be:
from PIL import Imageimage = Image.open('ed_sample.png')pixels = image.load()pixels[100, 100] = (255, 0, 0)pixel_value = pixels[100, 100]image.save('./output/ed_modified.png')
Code explanation:
Line 7: In this line, we access the pixel at (100, 100) in the image and assign the value (255, 0, 0)
to only have the red component.
If we zoom in on the image in the output, we may be able to spot a red pixel in the upper left of the portion of the image. But changing the value of a single pixel is not enough; let’s see how we can apply changes to the entire image.
If you want to know how to write text on an image using PIL, visit our Answer on How to write text on an image in Python.
We can iterate over all the pixels in an image using nested loops. This is useful for applying transformations or filters to the entire image.
from PIL import Imageimage = Image.open('ed_sample.png')pixels = image.load()width, height = image.sizetotal_pixels = 0for x in range(width):for y in range(height):total_pixels += 1print(total_pixels)
Code explanation:
Line 7: This line retrieves the image’s dimensions using the Image
object’s size
attribute and outputs them in a two-value tuple. We save this tuple’s first and second elements in variables width
and height
, respectively.
Line 9: We initialize a variable total_pixels
to 0 and use it to count the total number of pixels in the image.
Lines 11–12: These lines implement nested loops to iterate over all the pixels in the image. The outer loop iterates over the x-coordinates (from 0 to width-1
), and the inner loop iterates over the y-coordinates (from 0 to height-1
).
Line 13: This line increments the total_pixels
variable by 1 for each pixel processed and effectively counts the total number of pixels in the image.
Here is an example of applying a simple filter that directly converts an image to grayscale by manipulating pixel values. To convert the pixels to grayscale, we can use a weighted sum formula known as the luminance or brightness of the pixel, and it reflects how the human eye perceives the intensity of each color in the image.
from PIL import Imageimage = Image.open('ed_sample.png')pixels = image.load()width, height = image.sizefor x in range(width):for y in range(height):r, g, b = pixels[x, y]gray = int(0.299 * r + 0.587 * g + 0.114 * b)pixels[x, y] = (gray, gray, gray)image.save('./output/ed_modified.png')
Code explanation:
Line 11: This line retrieves the color components (red, green, blue) of the pixel at coordinates (x, y) using the pixels
object and unpacked the values into the variables r
, g
, and b
.
Line 12: This line calculates the pixel’s grayscale value using the formula we discussed earlier.
Line 13: Since grayscale images have equal values for the red, green, and blue components, we set each tuple to (gray, gray, gray)
, where gray
is the computed grayscale value.
If you want to know how to enhance an image in PIL, visit our Answer on How to enhance image in Python pillow.
Controlling images at a pixel level in Python with Pillow provides a powerful way to manipulate and transform images. By accessing and modifying individual pixels, we can apply custom filters, enhance images, and create unique visual effects, just to say the least. Some advanced use cases of pixel-level data include data compression and optimization, scientific and medical imaging, and enhanced graphics and game development. Whether we’re a beginner or an experienced programmer, understanding pixel-level image control opens up a wide range of possibilities for our Python projects.
Haven’t found what you were looking for? Contact Us
Free Resources