Image Shape/Size | OpenCV vs Pillow | Python

Shape/size refers to the dimension of the image – width, height, and number of color channels. This tutorial will show you how to get the shape/size of an image in cv2 and PIL.

OpenCV

if cv2_img.ndim == 2:
  height, width = cv2_img.shape
  channels = 1
else:
  height, width, channels = cv2_img.shape

Pillow

Note: It is hard to get the number of channels directly from a Pillow image object, the easier way is to first convert it to an OpenCV image (Numpy ndarray) and then get the shape.

width, height = pil_img.size 
cv2_img = np.array(pil_img)
if cv2_img.ndim == 2:
  channels = 1
else:
  channels = cv2_img.shape[-1]

Full Example

OpenCV

import cv2

# read image
cv2_img = cv2.imread("test_images/test1.jpg")

# get the image shape
if cv2_img.ndim == 2:
  height, width = cv2_img.shape
  channels = 1
else:
  height, width, channels = cv2_img.shape

# print the shape
print(f"({height}, {width}, {channels})")

Pillow

from PIL import Image
import numpy as np  # remember to import numpy

# read image
pil_img = Image.open("test_images/test1.jpg")

# get the image shape
width, height = pil_img.size 
cv2_img = np.array(pil_img)
if cv2_img.ndim == 2:
  channels = 1
else:
  channels = cv2_img.shape[-1]

# print the shape
print(f"({height}, {width}, {channels})")

References

Avatar photo
Steins

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