![]()
With Pillow, an image is a grid of pixels plus a mode that says how each pixel is represented. Open the file first, then inspect the mode and dimensions before assuming what its pixel values will look like.
from PIL import Image
image = Image.open("photo.jpg")
print(image.size) # (width, height)
print(image.mode) # often "RGB" for a JPEG
Opening an image is usually lazy: Pillow may read the file’s metadata before decoding all its pixels. Call load() when you want to force decoding, or use a context manager so the file is closed once you have finished reading it.
with Image.open("photo.jpg") as source:
source.load()
image = source.copy()
print(image.size)
The mode matters. An RGB pixel is a tuple of three channel values, each usually between 0 and 255. RGBA adds an alpha channel for transparency. A grayscale image may use L, where each pixel is a single value. Convert deliberately when your code depends on a particular representation.
from PIL import Image
with Image.open("input.png") as source:
image = source.convert("RGB")
print(image.mode)
Coordinates start at the upper-left corner: (0, 0) is the first pixel, x increases to the right, and y increases downward. This makes a small crop easy to inspect without printing an entire image.
pixel = image.getpixel((10, 20)) print(pixel) patch = image.crop((0, 0, 32, 32)) print(patch.size)
The crop box is (left, upper, right, lower); its right and lower edges are excluded. For large images, avoid repeatedly calling getpixel() in a Python loop. It’s useful for checking a few coordinates, while bulk pixel work is better handled through Pillow’s pixel access object or array tools.
Now loading...
Reading and changing pixel values
For a few pixels, getpixel() and putpixel() make the operation clear. For a sequence of edits, use load() once and index the resulting pixel access object with (x, y). It reads and writes the image directly.
pixels = image.load() red, green, blue = pixels[10, 20] pixels[10, 20] = (0, 0, 0)
A common mistake is to loop over the whole image and call a higher-level method for every pixel. Direct pixel access is simpler for small transformations, but Python still has to execute the loop one pixel at a time. Keep the image dimensions in mind, and do only the work the transformation requires.
pixels = image.load()
width, height = image.size
for y in range(height):
for x in range(width):
red, green, blue = pixels[x, y]
pixels[x, y] = (255 - red, 255 - green, 255 - blue)
This inverts each channel independently. The order of coordinates in pixels[x, y] is easy to confuse with the order of rows and columns: the outer loop walks down the image, while the inner loop walks across it. A row-wise rewrite often makes that relationship more obvious.
pixels = image.load()
width, height = image.size
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
average = (r + g + b) // 3
pixels[x, y] = (average, average, average)
That computes a simple grayscale value by averaging the channels. It’s not the same as a perceptual brightness calculation, because human vision is more sensitive to green than to blue. If the image is already in mode L, each pixel is a single integer rather than a tuple, so code written for RGB pixels will need to change.
gray = image.convert("L")
pixels = gray.load()
for y in range(gray.height):
for x in range(gray.width):
pixels[x, y] = 255 - pixels[x, y]
For an RGBA image, assignments need four values. The alpha channel controls opacity, so changing RGB while leaving alpha alone preserves the existing transparency.
image = image.convert("RGBA")
pixels = image.load()
r, g, b, alpha = pixels[10, 20]
pixels[10, 20] = (255 - r, 255 - g, 255 - b, alpha)
Pixel access objects are convenient, but they’re not a general-purpose array interface. When an operation applies the same arithmetic to every pixel, Pillow’s point operation can move that work into optimized code. It accepts a function or lookup table and applies it to channel values.
gray = image.convert("L")
negative = gray.point(lambda value: 255 - value)
For a threshold, a lookup table avoids calling a Python function once for every pixel. Each possible grayscale value maps to either black or white, and Pillow applies the table across the image.
gray = image.convert("L")
table = [0 if value 128 else 255 for value in range(256)]
binary = gray.point(table)
When editing selected pixels, test the condition on the original value before replacing it. Otherwise, a change made early in the loop can affect a later test if the condition depends on pixels already modified; keeping a separate source image is a simple way to make every decision from the same input.
source = image.convert("RGB")
result = source.copy()
src = source.load()
dst = result.load()
for y in range(source.height):
for x in range(source.width):
r, g, b = src[x, y]
if r > 200 and g 80 and b 80:
dst[x, y] = (255, 255, 0)
This replaces strongly red pixels with yellow while leaving the source unchanged. The threshold is deliberately crude: a pixel’s RGB values depend on lighting, and a red object in shadow may fall outside the test. A more reliable selection often compares channels or uses a color space that separates hue from brightness, which changes what the condition should measure.
Analyzing color and image structure
Color statistics are often more useful than inspecting individual pixels. ImageStat reports per-channel means and standard deviations; convert to a known mode first so the statistics have a predictable shape.
from PIL import Image, ImageStat
with Image.open("photo.jpg") as source:
rgb = source.convert("RGB")
stats = ImageStat.Stat(rgb)
print(stats.mean)
print(stats.stddev)
A mean can hide important structure. An image split evenly between black and white has the same average brightness as a uniform gray image. The histogram shows how many pixels occur at each channel value, which helps distinguish those cases.
gray = rgb.convert("L")
histogram = gray.histogram()
dark = sum(histogram[:64])
midtones = sum(histogram[64:192])
bright = sum(histogram[192:])
print(dark, midtones, bright)
The grayscale histogram has 256 entries, one for each intensity from zero to 255. For an RGB image, histogram() returns three consecutive 256-entry channel histograms. Separate them before comparing channel distributions.
histogram = rgb.histogram() red_histogram = histogram[0:256] green_histogram = histogram[256:512] blue_histogram = histogram[512:768] print(max(red_histogram), max(green_histogram), max(blue_histogram))
For images with few distinct colors, getcolors() returns counts paired with pixel values. It can return None if the number of distinct colors exceeds the supplied limit, so it isn’t a safe way to enumerate colors in an arbitrary photograph.
small = rgb.resize((64, 64))
colors = small.getcolors(maxcolors=64 * 64)
if colors is not None:
colors.sort(reverse=True)
print(colors[:10])
Resizing first gives a quick approximate palette without requiring a full-resolution color count. For a more compact summary of a photograph, quantize it to a fixed number of palette colors and count the resulting pixels.
palette_image = rgb.quantize(colors=8)
palette = palette_image.getpalette()
counts = palette_image.getcolors()
for count, index in sorted(counts, reverse=True):
start = index * 3
color = tuple(palette[start:start + 3])
print(count, color)
The palette index is not itself an RGB value; it selects three entries in the palette. Quantization is approximate, and the selected colors depend on the image and quantization method, so use it to summarize or group colors rather than to test exact color identity.
Image structure can be examined by comparing neighboring pixels or by applying an edge filter. The FIND_EDGES filter emphasizes places where intensity changes quickly; converting to grayscale first makes the result independent of the original channel layout.
from PIL import ImageFilter
gray = rgb.convert("L")
edges = gray.filter(ImageFilter.FIND_EDGES)
print(edges.getbbox())
getbbox() returns the smallest box containing nonzero pixels, or None if the image is entirely zero. The filter’s output is still an image, so a threshold can turn its gradual edge strengths into a binary mask this is easier to count or inspect.
table = [0 if value 40 else 255 for value in range(256)] edge_mask = edges.point(table) print(edge_mask.getbbox()) print(sum(edge_mask.histogram()[1:]))
The count measures edge pixels above the chosen threshold, not objects or boundaries in any semantic sense. A textured surface can produce many edges, while a low-contrast boundary can disappear; comparing the mask across regions can reveal where the image’s structure is concentrated.
Saving the results in useful formats
save() chooses a format from the filename extension when it can. If the destination is a file object, or the extension is ambiguous, pass the format explicitly. Pillow does not change the image’s format merely because you give the output a different extension.
from PIL import Image
with Image.open("input.png") as source:
image = source.convert("RGB")
image.save("output.jpg", format="JPEG")
Choose the format according to what the image needs. JPEG is useful for photographs and discards some image information to reduce file size. PNG is lossless and supports transparency. Saving an image with transparency as JPEG is not possible without first removing the alpha channel or compositing the image onto a background.
with Image.open("logo.png") as source:
rgba = source.convert("RGBA")
rgba.save("logo-copy.png", format="PNG")
background = Image.new("RGB", rgba.size, "white")
background.paste(rgba, mask=rgba.getchannel("A"))
background.save("logo-on-white.jpg", quality=90)
JPEG quality is a tradeoff between size and visible artifacts. A high setting usually preserves more detail, but repeatedly opening and saving a JPEG can accumulate damage. Keep an original or a lossless working copy, and create the compressed JPEG as an output rather than using it as the next input.
image.save(
"photo.jpg",
format="JPEG",
quality=88,
optimize=True,
progressive=True,
)
For PNG, optimize can reduce file size by trying different compression strategies; it does not make the image lossy. Palette images can be smaller when they contain few colors, but converting a photograph to a palette may introduce visible color changes.
with Image.open("chart.png") as source:
indexed = source.convert("P", palette=Image.Palette.ADAPTIVE, colors=128)
indexed.save("chart-indexed.png", optimize=True)
When creating a thumbnail, resize a copy so the original dimensions remain available for other outputs. thumbnail() modifies its image in place and preserves the aspect ratio while fitting within the requested bounds.
with Image.open("photo.jpg") as source:
thumbnail = source.convert("RGB")
thumbnail.thumbnail((320, 320))
thumbnail.save("photo-small.jpg", quality=85)
Saving pixel data does not necessarily preserve every property of the source file. If metadata matters, pass the relevant metadata explicitly and check that the destination format supports it. For example, JPEG EXIF data can be supplied with the exif argument.
with Image.open("camera.jpg") as source:
exif_data = source.getexif()
image = source.convert("RGB")
image.save("copy.jpg", quality=90, exif=exif_data)
For a batch of files, derive the output name from the input path and choose the output format explicitly. This avoids accidentally overwriting the source and makes the conversion policy visible in the code.
from pathlib import Path
from PIL import Image
input_dir = Path("images")
output_dir = Path("converted")
output_dir.mkdir(exist_ok=True)
for path in input_dir.glob("*.png"):
with Image.open(path) as source:
output = source.convert("RGB")
destination = output_dir / f"{path.stem}.jpg"
output.save(destination, format="JPEG", quality=88)
Source: https://www.pythonfaq.net/how-to-manipulate-pixels-and-analyze-images-with-pillow-in-python/
