top of page
GeoWGS84AI_Logo_edited.jpg

Python Pillow Tutorial: From Basics to Advanced Image Editing

10 minutes ago
4 min read

Image processing is an integral part of software development, computer vision, web development, digital content generation, and geospatial data processing. There are a few image processing libraries available in Python. Pillow is considered to be the most commonly used image processing tool.


Pillow is an open-source image library written in Python. It allows users to perform operations like opening, manipulating, and saving different images from various formats. Pillow is considered the improved version of the PIL (Python Imaging Library). Using this library, one can easily perform operations on images without the need for image processing software.


Python Pillow
Python Pillow

What is Python Pillow?


Pillow is an imaging library for Python that offers features to work with raster graphics by manipulating them, changing their properties, and saving to a specific format. Formats supported include JPEG, PNG, GIF, BMP, TIFF, and WebP, where format support depends on the build and codecs installed.


Pillow can be used for:


  • Image resizing and cropping

  • Image conversion between formats

  • Adjusting brightness, contrast, and colors

  • Drawing text, shapes, and watermarks

  • Using image filters and enhancements

  • Batch processing of several images

  • Preparing images for web and ML purposes.


How to Install Pillow in Python


Ensure that both Python and pip are installed on your computer before proceeding with the Pillow installation process.


The Pillow installation command is as follows:


python -m pip install Pillow


To check whether you have correctly installed Pillow, use:


from PIL import Image


print(Image.__version__)


Although the name of the package that can be installed via pip is "Pillow," the PIL namespace is used in order to remain compatible with the original imaging library.


Opening and Displaying Images with Pillow


Image class is the main module used in Pillow. It allows you to open images, access image information, modify pixels, and save the output.


from PIL import Image


image = Image.open("input.jpg")


print("Image format:", image.format)

print("Image size:", image.size)

print("Color mode:", image.mode)


image.show()


Size returns the dimensions of the image in pixels, and mode returns the pixel representation of the image, which could be RGB, RGBA, or grayscale (L).


Resizing and Cropping Images


Resizing images is often employed when working on optimizing images for websites, creating thumbnails, and preparing visual data for machine learning applications.


from PIL import Image


image = Image.open("input.jpg")


resized_image = image.resize((800, 600))

resized_image.save("resized_image.jpg")


The above code resizes the image to 800 by 600 pixels. Specifying the new dimensions will, however, affect the aspect ratio of the original image. To keep the proportions, the thumbnail() function can be used:


from PIL import Image


image = Image.open("input.jpg")

image.thumbnail((800, 800))

image.save("thumbnail.jpg")


The thumbnail() function changes the size of the image in-place and keeps it inside the specified bounding box.


To crop a certain area of the image, the coordinates of the rectangle that defines this area should be set:


from PIL import Image


image = Image.open("input.jpg")


cropped = image.crop((100, 100, 500, 400))

cropped.save("cropped_image.jpg")


Advanced Image Editing with Pillow


Apart from simple operations, Pillow provides advanced methods related to image compositing, transparency handling, channel handling, and pixel operations.


Image Compositing and Transparency


The RGBA mode has red, green, blue, and alpha channels. The alpha channel is responsible for transparency.


from PIL import Image


background = Image.open("background.png").convert("RGBA")

overlay = Image.open("overlay.png").convert("RGBA")


background.alpha_composite(overlay)

background.save("composite.png")


The overlay image should fit in the destination image in this case. For smaller overlay images and different positioning, use the alpha_composite() method with an appropriate destination image.


Image Pixel-level Manipulation


The Pillow library also supports manipulation of individual pixels as well as the image channels.


from PIL import Image


image = Image.open("input.jpg").convert("RGB")


pixel = image.getpixel((100, 100))

print("Pixel RGB value:", pixel)


image. putpixel((100, 100), (255, 0, 0))

image.save("modified_image.jpg")


The manipulation of individual pixels is useful in custom image manipulation and computer vision education. When working with large-scale number manipulations, however, NumPy is preferred.


Automating Batch Image Processing


Developers can use batch processing to transform images consistently without editing each of them by hand.


from pathlib import Path

from PIL import Image


input_folder = Path("images")

output_folder = Path("processed_images")

output_folder.mkdir(exist_ok=True)


for file_path in input_folder.iterdir():

if file_path.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp"}:

try:

with Image.open(file_path) as image:

image.thumbnail((1200, 1200))

output_path = output_folder / f"{file_path.stem}.jpg"

image.convert("RGB").save(

output_path,

"JPEG",

quality=90,

optimize=True

)

except (OSError, ValueError) as error:

print(f"Could not process {file_path}: {error}")


This code reads supported input images, resizes them, transforms them into RGB format, and writes out the results as JPEG images in another folder. When using the code in production, pay attention to the types of images and to transparency, because the transformation from RGBA to RGB drops the alpha channel.


Python Pillow Applications in GIS and Remote Sensing


The library can be used for processing images in Geographic Information Systems (GIS), remote sensing, and geospatial data visualization. These include resizing preview images in satellite maps, thumbnail generation for cataloging of aerial imagery, labeling of exported maps, and conversion of image formats for use in web applications.


It must be noted that Pillow should not be considered a substitute for geospatial libraries. This is because Pillow does not facilitate the workflow for coordinate reference system transformations, georeferencing, raster reprojections, and geospatial metadata preservation. For GeoTIFFs and geospatial raster analysis, libraries like Rasterio, GDAL, and Xarray can be better alternatives.


Pillow Python library can be used to automate the process of editing images, their format conversion, image resizing, filtering, labeling, and even processing images in batch.


Using the Pillow library together with NumPy, OpenCV, Rasterio, and other Python libraries, you can create effective workflows for web development, computer vision, digital imaging, and geospatial visualization purposes.


Whether you need to prepare your images for use on the website or create an automated process for image processing, learning Python Pillow will be helpful.


To learn more about Pillow and its geospatial capabilities, click here.


For more information or any questions regarding the LizardTech suite of products, please don't hesitate to contact us at:



USA (HQ): (720) 702–4849


(A GeoWGS84 Corp Company)



 
 
 

Comments


bottom of page