The Ultimate Handbook for OpenCV & Pillow

Steins
Analytics Vidhya
Published in
7 min readSep 12, 2021

--

Introduction

OpenCV and Pillow are the commonly used libraries in Python for image processing.

In this article, I will list out all the codes that are useful regarding OpenCV and Pillow side by side, so that you can compare them easily.

New Version

Please note that all the new content and full versions of this tutorial will be moved to CodoRaven.com > OpenCV vs Pillow.

Updates

  • 15-Jun-22: Added [13. RGBA to RGB].
  • 16-Jul-22: Added “specify background color” to [6. Rotate].
  • 28-Jan-23: Updated Image.ANTIALIAS to Image.Resampling.LANCZOS [5. Resize].
  • 29-Jan-23: Updated np.float to np.float32; Image.PERSPECTIVE to Image.Transform.PERSPECTIVE; Image.BICUBIC to Image.Resampling.BICUBIC [10. Warp / Transform].

0. Install & Import

To install Pillow and OpenCV, please type the following in your terminal (replace pip with pip3 if your python3 is using pip3):

pip install numpy
pip install opencv-python
pip install Pillow

Before using them, you have to import them into your python file with the following codes:

from PIL import Image
import cv2
import numpy as np

Note: Since OpenCV images are actually NumPy arrays, we would also like to install and import the NumPy library.

1. Read

Read/open a colorful image:

pil_img = Image.open("your_image.jpg")  # RGBcv2_img = cv2.imread("your_image.jpg")  # BGR

Read/open a grayscale image:

pil_img = Image.open("your_image.jpg").convert("L")cv2_img = cv2.imread("your_image.jpg", cv2.IMREAD_GRAYSCALE)

More examples:

2. Write

Write/save an image:

pil_img.save("new_image.jpg")

--

--

Steins
Analytics Vidhya

Developer & AI Researcher. Write about AI, web dev/hack. Be my referred member: https://medium.com/@steinsfu/membership. Support me: https://ko-fi.com/steinsfu