Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python OpenCV vs Pillow: Choosing the Right Image Library

Compare OpenCV and Pillow for Python image processing: how they store images, where their APIs differ, and how to choose the right library for your project.

~7 min readPython
#OpenCV#Pillow#Image Processing#Computer Vision
A split illustration showing a Pillow logo and an OpenCV logo with an image being processed between them, representing the comparison of the two Python image libraries.

When you need to process images in Python, OpenCV and Pillow are two of the most common choices. Both can load images, resize them, and convert color spaces, but they are built for different problems. OpenCV is a computer vision framework with algorithms for detection, tracking, and geometric transformations. Pillow is a focused imaging library that excels at file format support, pixel-level manipulation, and simple batch operations. The right choice depends on whether you are building a vision pipeline or just need reliable image I/O and basic edits.

What Each Library Actually Provides

Pillow (the modern fork of the Python Imaging Library) reads and writes many image formats, including PNG, JPEG, GIF, TIFF, and WebP. Its core data structure is the Image object, which provides direct access to pixel data plus filters, drawing operations, and color space conversions. Pillow has a Python API with C extensions for performance-critical work, and it integrates easily with web frameworks and scripts.

OpenCV (Open Source Computer Vision Library) is a C++ library with Python bindings. Its primary data structure is numpy.ndarray, so images are arrays of pixel values. OpenCV includes hundreds of functions for feature detection, object recognition, camera calibration, and video analysis, as well as optimized implementations of common operations such as filtering, thresholding, and morphological transformations. OpenCV is not a drop-in replacement for Pillow; it is a broader toolkit.

The key distinction is scope. Pillow solves the problem of “read, modify, save an image.” OpenCV solves the problem of “analyze and understand an image.” If you are cropping a photo for a web thumbnail, Pillow is enough. If you are detecting faces in a live video stream, you need OpenCV.

Core Differences in Image Handling

The two libraries represent images differently, which affects every operation you perform.

AspectPillowOpenCV
Data structurePIL.Image.Imagenumpy.ndarray
Color orderRGB by defaultBGR by default
Pixel accessgetpixel() / putpixel()Direct array indexing
Coordinate systemTop-left origin, y downSame, but array indexing is [row, col]
Format supportExtensive, including WebP, GIF, ICOLimited to common formats via imread/imwrite
Video supportNoneBuilt-in VideoCapture
Advanced algorithmsMinimalExtensive (feature detection, optical flow, etc.)

These differences matter in practice. OpenCV’s default BGR order is a common source of confusion when displaying images with matplotlib. Pillow’s RGB order is more intuitive for web developers. Also, OpenCV’s array-based representation makes it natural to use NumPy operations for custom transformations, while Pillow’s Image object hides the pixel buffer behind a higher-level API.

Syntax and API Comparison

Here are equivalent operations in both libraries.

Loading and Saving

python
# Pillow from PIL import Image img = Image.open('photo.jpg') img.save('photo.png') # OpenCV import cv2 img = cv2.imread('photo.jpg') cv2.imwrite('photo.png', img)

Pillow’s Image.open() is lazy; it reads the file header and delays full decoding until you access pixels or save. OpenCV’s imread() loads and decodes the image immediately. For metadata-only work, Pillow can avoid the full decode.

Resizing

python
# Pillow resized = img.resize((800, 600)) # OpenCV resized = cv2.resize(img, (800, 600))

Both use different interpolation methods by default. Pillow uses NEAREST unless you specify otherwise, which can produce jagged edges. OpenCV defaults to INTER_LINEAR, which is smoother. For high-quality downscaling, explicitly set interpolation in both libraries.

Color Conversion

python
# Pillow gray = img.convert('L') # OpenCV gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Pillow’s convert method is concise and handles many mode conversions (RGB, RGBA, L, CMYK, etc.). OpenCV requires you to specify the source and destination color spaces. This is more verbose but also more explicit, which helps when you are working with video frames or camera input.

Pixel Access

python
# Pillow pixel = img.getpixel((x, y)) img.putpixel((x, y), (255, 0, 0)) # OpenCV pixel = img[y, x] # note: row, column order img[y, x] = [255, 0, 0] # BGR

Pillow’s getpixel and putpixel are convenient for occasional reads, but Python-level pixel loops are slow in both libraries. OpenCV’s ndarray representation is better for bulk operations because it can use NumPy’s vectorized operations.

Performance and Memory Considerations

Performance differences between OpenCV and Pillow come from their underlying implementations and data structures. OpenCV is heavily optimized for real-time work; many functions use SIMD instructions and multi-threading. Pillow’s C backend is also fast for I/O and common filters, but it is not designed for high-throughput computer vision tasks.

For example, Gaussian blur is available in both libraries. OpenCV’s implementation is often faster for repeated filtering on large images, while Pillow’s ImageFilter.GaussianBlur is adequate for one-off edits but may be slower in a loop processing thousands of frames.

Memory usage also differs. OpenCV stores images as NumPy arrays, so you can slice them, pass them to other NumPy-based tools, and reuse buffers in video pipelines. Pillow’s Image object is higher-level; operations such as crop() create a new Image, and memory-sharing behavior depends on the operation. Neither library is inherently better; the right choice depends on the operation.

When to Use Pillow

Pillow is the right tool when your task is primarily image I/O and basic manipulation. Common scenarios include:

  • Generating thumbnails for a web application.
  • Converting between formats (for example, PNG to JPEG) with control over quality.
  • Adding text, watermarks, or simple shapes to images.
  • Reading image metadata (EXIF, etc.) without decoding the full image.
  • Working with GIFs or animated images.

Pillow’s API is more Pythonic and easier to learn for developers who do not need computer vision. It also integrates well with Django and Flask, where you might process uploaded images in a request handler. Pillow does not require NumPy as a dependency, so it can keep a minimal environment lighter than an OpenCV installation.

When to Use OpenCV

OpenCV is the standard choice for computer vision tasks, but it is also useful for advanced image processing that goes beyond what Pillow offers. Use OpenCV when you need:

  • Object detection (faces, pedestrians, custom models).
  • Feature matching (SIFT, ORB, etc.).
  • Video capture and processing from webcams or files.
  • Geometric transformations such as perspective correction and image stitching.
  • Real-time processing with low latency.
  • Integration with NumPy for custom algorithms.

OpenCV also provides a wider set of filtering and interpolation options. cv2.warpAffine and cv2.warpPerspective are important for image registration and alignment. Pillow’s Image.transform can do basic affine or perspective mappings, but OpenCV’s geometric transform toolkit is more complete.

If you are already using NumPy for data analysis, OpenCV’s array-based API fits naturally. You can apply NumPy operations to an image, then use OpenCV to visualize or save it.

Combining Both Libraries in One Project

You do not have to choose one exclusively. Many production systems use both. A common pattern is to load an image with Pillow, perform format-specific preprocessing, convert it to a NumPy array for OpenCV processing, then convert back to Pillow for saving.

python
from PIL import Image import numpy as np import cv2 # Load with Pillow to handle unusual formats or metadata pil_image = Image.open('input.tiff') # Convert to RGB (Pillow uses RGB) rgb_array = np.array(pil_image.convert('RGB')) # OpenCV expects BGR, so reverse the channels bgr_array = cv2.cvtColor(rgb_array, cv2.COLOR_RGB2BGR) # Now use OpenCV functions processed = cv2.GaussianBlur(bgr_array, (5, 5), 0) # Convert back to Pillow for saving as GIF or another format result_rgb = cv2.cvtColor(processed, cv2.COLOR_BGR2RGB) result_pil = Image.fromarray(result_rgb) result_pil.save('output.gif')

The conversion creates a new array, but for a single image the overhead is usually small. If you later slice an array and an OpenCV function requires contiguous memory, call np.ascontiguousarray() before passing it in.

Decision Criteria for Your Project

To decide between OpenCV and Pillow, evaluate the following conditions:

  • Primary task: If you are doing computer vision (detection, tracking, recognition), choose OpenCV. If you are doing simple edits or format conversion, choose Pillow.
  • Performance requirements: For real-time or batch processing of many images, OpenCV’s optimized functions are a better fit. For occasional one-off operations, Pillow is fine.
  • Dependencies: If you want to avoid NumPy and keep your environment small, Pillow is the lighter choice.
  • API familiarity: Pillow’s API is more intuitive for beginners. OpenCV’s function names and argument orders have a steeper learning curve.
  • Integration: If you are already using NumPy or need to pass images to a machine learning model, OpenCV’s array format is more convenient.

There is no universal winner. For a web service that resizes user uploads, Pillow is sufficient. For an autonomous vehicle project, OpenCV is essential. Understanding the strengths of each library helps you pick the right tool without carrying unnecessary dependencies.

Handling Color Order Mismatches

One of the most common pitfalls when working with both libraries is color channel order. Pillow uses RGB; OpenCV uses BGR. If you load an image with OpenCV and then try to display it with a library that expects RGB (such as matplotlib), the red and blue channels will be swapped. Similarly, if you convert a Pillow image to a NumPy array and pass it to OpenCV without reversing channels, your colors will be wrong.

Always be explicit about the color space when converting between libraries. Use cv2.cvtColor with COLOR_RGB2BGR or COLOR_BGR2RGB as appropriate. This small step prevents hours of debugging.

Another subtlety is the data type. Pillow images are typically 8-bit unsigned integers, while OpenCV can handle 16-bit and 32-bit float arrays for operations that support them. When converting from Pillow to OpenCV, ensure the array is contiguous and has the correct dtype. Using np.array(pil_image) is the usual way to get an array; if you have sliced it, call np.ascontiguousarray() before passing it to OpenCV.

These details matter in production, where a color shift or a type mismatch can corrupt the output. By understanding the underlying data structures, you can write conversion code that is robust and maintainable.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.