Read Image | OpenCV vs Pillow | Python

Here are the side-by-side comparisons of using OpenCV (cv2) and Pillow (PIL) to read/open images in RGBA/RGB/grayscale.

Please note that the color channels are ordered differently in Pillow and OpenCV images:

Pillow (PIL)OpenCV (cv2)
Colorful imageRGBBGR
Transparent imageRGBABGRA
Images of different color spaces
Images of different color spaces

1. Read a Colorful Image (RGB)

# Pillow (RGB)
pil_img = Image.open("your_image.jpg")

# OpenCV (BGR)
cv2_img = cv2.imread("your_image.jpg")

2. Read a Transparent Image (RGBA)

# Pillow (RGBA)
pil_img = Image.open("your_image.png")

# OpenCV (BGRA)
cv2_img = cv2.imread("your_image.png", cv2.IMREAD_UNCHANGED)

3. Read Into a Grayscale Image

# Pillow
pil_img = Image.open("your_image.jpg").convert("L")

# OpenCV
cv2_img = cv2.imread("your_image.jpg", cv2.IMREAD_GRAYSCALE)

Full Example

You might also want to learn how to show images using cv2 and PIL.

Pillow

from PIL import Image

# read colorful image
pil_img_jpg = Image.open("test_images/test1.jpg")
# read transparent image
pil_img_png = Image.open("test_images/test2.png")
# read into grayscale image
pil_img_gray = Image.open("test_images/test1.jpg").convert("L")

# show images
pil_img_jpg.show("pil image jpg")
pil_img_png.show("pil image png")
pil_img_gray.show("pil image gray")

OpenCV

import cv2

# read colorful image
cv2_img_jpg = cv2.imread("test_images/test1.jpg")
# read transparent image
cv2_img_png = cv2.imread("test_images/test2.png", cv2.IMREAD_UNCHANGED)
# read into grayscale image
cv2_img_gray = cv2.imread("test_images/test1.jpg", cv2.IMREAD_GRAYSCALE)

# show images
cv2.imshow("cv2 image jpg", cv2_img_jpg)
cv2.imshow("cv2 image png", cv2_img_png)
cv2.imshow("cv2 image gray", cv2_img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

Syntax

Pillow

PIL.Image.open(fp, mode='r', formats=None)

Parameters:

  • fp: A filename (string), pathlib.Path object, or file object. The file object must implement file.read, file.seek, and file.tell methods, and be opened in binary mode.
  • mode: The mode. If given, this argument must be “r”.
  • formats: A list or tuple of formats to attempt to load the file. This can be used to restrict the set of formats checked. Pass None to try all supported formats. You can print the available formats by running python3 -m PIL or using the PIL.features.pilinfo() function.

Returns:

  • An Image object.

OpenCV

cv2.imread(filename[, flags])

Parameters:

  • filename: Name of file to be loaded.
  • flags: Flag that can take values of cv::ImreadModes.

Returns:

  • An image (Numpy array).

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.