Python & Data Science

Image Processing In Python With Pillow Resizing Fi

You just downloaded 1,000 product photos for your new classification model. The first one is 4,000 pixels wide and crystal clear. The second is a grainy 200x200 thumbnail. The third has a transparent background. The fourth is sideways.

Sound familiar? If you’ve ever tried to build a model on real-world images, you know this pain. Your model doesn’t care about artistic composition or high resolution. It cares about one thing: consistent input size. Every image must be the same width, height, and color format, or your model will fail — silently and frustratingly.

Do you really need every pixel? No. Most models downsample images to 224x224 or 299x299 anyway. The hard part isn’t the math. It’s the boring preprocessing that decides whether your model works or not.

Enter Pillow. It’s the simplest, most widely used image processing library in Python. It’s built into most environments, and you can install it with one line:

pip install Pillow

Let’s start by opening an image and seeing what we’re working with.

from PIL import Image

# Open an image file
img = Image.open("example.jpg")

# Print its properties
print(f"Format: {img.format}")
print(f"Size: {img.size}")
print(f"Mode: {img.mode}")

Here’s what that output means in plain English:

  • Format: The file type (JPEG, PNG, etc.). Your model doesn’t care about this, but your storage does.
  • Size: A tuple like (4000, 3000). That’s width x height in pixels. This is what we need to standardize.
  • Mode: The color space. ‘RGB’ means full color. ‘L’ means grayscale. ‘RGBA’ means color plus transparency. Most models expect RGB.

This is the first step. You now know exactly what you’re dealing with. Let’s fix it.

Resizing: More Than Just Resizing

The most common operation is resizing. But if you just set a width and height blindly, you’ll stretch images and ruin aspect ratios. Let’s see what that looks like.

from PIL import Image

# Open an image (assume it's a rectangular cat photo)
img = Image.open("cat.jpg")
print(f"Original size: {img.size}")

# Naive resize — this will stretch the image
img_stretched = img.resize((300, 300))
print(f"Stretched size: {img_stretched.size}")

The image is now 300x300, but the cat looks squished or stretched. That’s because the original aspect ratio (width divided by height) was different from 1:1.

What’s actually going on here? The aspect ratio is the relationship between width and height. If your image is 4000x3000, the ratio is 4:3. If you force it to 1:1, you distort the image.

The fix is simple: calculate a scaling factor that preserves the ratio.

from PIL import Image

img = Image.open("cat.jpg")

# Target width
base_width = 300

# Calculate height to preserve aspect ratio
w_percent = base_width / float(img.size[0])
h_size = int(float(img.size[1]) * float(w_percent))

# Resize with aspect ratio preserved
img_resized = img.resize((base_width, h_size), Image.LANCZOS)
print(f"Resized with ratio: {img_resized.size}")

Your image is now 300 pixels wide, and the height automatically adjusts. No distortion. The cat looks like a cat.

Now here’s the interesting part: Pillow gives you six different filters to control how it guesses the missing pixels when you shrink an image. Think of them as different ways of averaging neighboring pixels:

  • NEAREST: Fastest, but blocky. Just picks the closest pixel.
  • BILINEAR: Medium quality. Averages 4 surrounding pixels.
  • BICUBIC: Better. Averages 16 surrounding pixels.
  • LANCZOS: Best quality, slowest. Looks at a wider neighborhood (up to 36 pixels).

For most preprocessing, use Image.LANCZOS. The quality difference matters when you’re feeding images into a model that will magnify every artifact.

There’s also a shortcut: thumbnail(). It does the same thing as our manual calculation, but it never upscales — it only shrinks images. Perfect for creating consistent dataset sizes without accidentally blowing up tiny images.

from PIL import Image

img = Image.open("cat.jpg")
img.thumbnail((300, 300), Image.LANCZOS)
print(f"Thumbnail size: {img.size}")

This is the hardest part of resizing: remembering to preserve the aspect ratio. Once you do, everything else is easy.

Filters: The Smoke and Mirrors of Image Processing

Filters are where image processing feels like magic. But what’s actually going on? A filter is just a small matrix sliding over the image, changing each pixel based on its neighbors.

Let’s start with the most intuitive filter: blur. A blurry image is one where every pixel is an average of its neighbors. It smudges detail and removes noise.

from PIL import Image, ImageFilter

img = Image.open("cat.jpg")

# Apply a blur filter
img_blurred = img.filter(ImageFilter.BLUR)
img_blurred.save("cat_blurred.jpg")

# Apply a sharpen filter
img_sharpened = img.filter(ImageFilter.SHARPEN)
img_sharpened.save("cat_sharpened.jpg")

What does this mean for your model? A blurry image removes high-frequency noise — those tiny pixel variations that confuse a model. A sharp image boosts edges, making features like whiskers and eyes stand out.

Now here’s the cool part: edge detection. It finds where colors change sharply — the boundaries between objects. This is how models learn to recognize shapes.

from PIL import Image, ImageFilter

img = Image.open("cat.jpg")

# Find edges
img_edges = img.filter(ImageFilter.FIND_EDGES)
img_edges.save("cat_edges.jpg")

The output is a black-and-white image where white pixels show the edges. This highlights where your model might find important features: the outline of the cat, the shape of its ears, the curve of its tail.

But wait — you don’t need to understand the math behind convolution matrices. You just need to know which filter does what:

  • BLUR: Removes noise, smooths details.
  • SHARPEN: Enhances edges, makes features pop.
  • FIND_EDGES: Highlights boundaries, useful for feature extraction.
  • SMOOTH: A gentler blur, good for reducing JPEG compression artifacts.

A practical tip for modeling: smooth before resizing. If you shrink a noisy image without smoothing, the noise gets compressed into the smaller image and becomes harder to remove. Smooth first, then resize.

from PIL import Image, ImageFilter

img = Image.open("cat.jpg")

# Smooth first, then resize
img_smoothed = img.filter(ImageFilter.SMOOTH)
img_smoothed.thumbnail((300, 300), Image.LANCZOS)
img_smoothed.save("cat_processed.jpg")

This is the smoke and mirrors: a few lines of code that dramatically improve your image quality before modeling.

Batch Editing: From One Image to a Thousand

Manually editing 1,000 images is not just boring — it’s impossible. The trick is to loop over a folder, apply the same operations to each image, and save with a consistent naming scheme.

Here’s the complete batch resize script:

import os
from PIL import Image, ImageFilter

# Folder paths
input_folder = "raw_images/"
output_folder = "processed_images/"

# Create output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)

# Target size
base_width = 300

# Loop through all files in the input folder
for filename in os.listdir(input_folder):
    # Only process image files
    if filename.lower().endswith((".jpg", ".jpeg", ".png", ".bmp")):
        try:
            # Open the image
            img_path = os.path.join(input_folder, filename)
            img = Image.open(img_path)

            # Handle RGBA to RGB conversion (for PNGs with transparency)
            if img.mode == "RGBA":
                img = img.convert("RGB")

            # Calculate new size preserving aspect ratio
            w_percent = base_width / float(img.size[0])
            h_size = int(float(img.size[1]) * float(w_percent))

            # Resize with LANCZOS filter
            img_resized = img.resize((base_width, h_size), Image.LANCZOS)

            # Save with original filename in output folder
            output_path = os.path.join(output_folder, filename)
            img_resized.save(output_path)

            print(f"Processed: {filename}")

        except Exception as e:
            print(f"Error processing {filename}: {e}")

In one loop, we’ve processed the entire folder. Each image is now 300px wide, high quality, ready for the next step.

Let’s break down what this code does:

  1. List all files: os.listdir() gets every filename in the folder.
  2. Filter by extension: We only process .jpg, .jpeg, .png, and .bmp files. This avoids trying to open text files or hidden system files.
  3. Handle transparency: PNG images often have an RGBA mode (Red, Green, Blue, Alpha for transparency). Most models expect RGB, so we convert.
  4. Preserve aspect ratio: Same calculation as before.
  5. Error handling: The try-except block catches corrupt images. You’ll learn this the hard way when your dataset has one broken file that crashes the entire loop.
  6. Save with original name: We keep the original filename to avoid collisions. You could also add a prefix like processed_ to distinguish processed files.

This is where you go from ‘I can edit one image’ to ‘I can edit an entire dataset.’

The Pipeline: Crop, Resize, Filter — Ready for Your Model

Now let’s put it all together into a preprocessing pipeline. Many convolutional neural networks (CNNs) expect square inputs — typically 224x224 for ResNet or VGG, or 299x299 for Inception.

Here’s the complete pipeline:

from PIL import Image, ImageFilter

def preprocess_image(input_path, output_path, output_size=(224, 224)):
    """
    Preprocess an image for model input:
    1. Crop center square
    2. Resize to exact dimensions
    3. Apply smoothing filter
    """
    # Open the image
    img = Image.open(input_path)

    # Handle RGBA to RGB conversion
    if img.mode == "RGBA":
        img = img.convert("RGB")

    # Step 1: Crop center square
    width, height = img.size
    min_dim = min(width, height)
    left = (width - min_dim) / 2
    top = (height - min_dim) / 2
    right = (width + min_dim) / 2
    bottom = (height + min_dim) / 2
    img_cropped = img.crop((left, top, right, bottom))

    # Step 2: Resize to exact dimensions
    img_resized = img_cropped.resize(output_size, Image.LANCZOS)

    # Step 3: Apply smoothing filter to reduce JPEG artifacts
    img_smoothed = img_resized.filter(ImageFilter.SMOOTH)

    # Save the result
    img_smoothed.save(output_path)
    print(f"Saved: {output_path}")

# Example usage
preprocess_image("cat.jpg", "cat_ready.jpg")

Your image is now 224x224, centered, smooth — exactly what your model expects. You’ve eliminated a common source of model failure.

Here’s what each step does:

  1. Crop center square: Most CNNs expect square inputs. We find the smaller dimension and crop a square from the center. This preserves the most important part of the image (the subject is usually in the center).

  2. Resize to exact dimensions: We force the image to exactly 224x224. Since we already cropped a square, there’s no distortion.

  3. Apply smoothing filter: JPEG compression creates blocky artifacts at low quality settings. A gentle smooth reduces these artifacts without losing important features.

You could also convert to grayscale here if your model uses single-channel input:

if img.mode != "L":
    img = img.convert("L")

This pipeline is reusable. Just change output_size and the filter for different architectures. For a ResNet, use 224x224. For Inception, use 299x299. For a model trained on sharp images, skip the smoothing.

What You’ve Learned

Let’s recap the key takeaways:

  • Open and inspect images: Know your format, size, and mode before doing anything.
  • Resize with aspect ratio preserved: Use thumbnail() or manual calculation with Image.LANCZOS for best quality.
  • Apply filters strategically: Blur removes noise, sharpen enhances features, edge detection highlights boundaries.
  • Batch process everything: One loop over a folder turns 1,000 messy images into a clean dataset.
  • Build a preprocessing pipeline: Crop center, resize, filter — in that order — for model-ready images.

This is the boring but essential step that separates working models from failing ones. Your model doesn’t care about artistic quality. It cares about consistency. Give it that, and it will reward you.

Check Your Understanding

Remember: What does the mode property of an image tell you?

Understand: Why is it important to preserve the aspect ratio when resizing?

Apply: Write a function that takes an image path and returns a 256x256 grayscale version with edges highlighted.

Analyze: You have a folder of images where some are landscape (wider than tall) and some are portrait (taller than wide). How would you crop them all to squares without losing the subject?

Evaluate: Compare the output of Image.LANCZOS vs Image.NEAREST on a small image (50x50) scaled up to 200x200. Which one looks better? Which one is faster?

Create: Design a preprocessing pipeline for a dataset of 10,000 product photos that includes: (1) center crop to square, (2) resize to 299x299, (3) convert to RGB, (4) apply a gentle sharpen filter. Write the complete batch processing script.

  • Data Augmentation in Python: Making More Data From Less — Learn how to artificially expand your dataset by applying random transformations to your preprocessed images.
  • Building a CNN From Scratch in PyTorch: A Step-by-Step Guide — See how your preprocessed images flow through a real convolutional neural network.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans

Looking for something else?

Search every article by title, summary or topic.