Get image size (width, height) with Python, OpenCV, Pillow (PIL) – Programming Code Examples
Python

Get image size (width, height) with Python, OpenCV, Pillow (PIL)3 min read

Python has a library that handles images such as OpenCV and Pillow (PIL). Here, the method of acquiring the image size (width, height) will be described.

In OpenCV, the image size (width, height) can be obtained as a tuple with the attribute shape of ndarray and the attribute size of PIL.Image in Pillow (PIL). Note that the order of width and height is different.




This article describes the following contents.

  • OpenCV: Get image size (width, height) with ndarray.shape
    • For color image
    • For grayscale (monochrome) images
  • Pillow (PIL): Get image size (width, height) with size,widthheight

OpenCV: Get image size (width, height) with ndarray.shape

When an image file is read by OpenCV, it is treated as NumPy array ndarray. The size (width, height) of the image can be acquired from the attribute shape indicating the shape of ndarray.

Not limited to OpenCV, the size of the image represented by ndarray, such as when an image file is read by Pillow and converted to ndarray, is obtained by shape.

For color image

In the case of a color image, it is a 3D ndarray of row (height) x column (width) x color (3)shape is a tuple of (row (height), column (width), color (3)).

When assigning each value to a variable, unpack the tuple as follows.

If you want to assign width and height to variables, you can apply the following to either color or grayscale images:

If you want to get a (width, height) tuple, you can use slice. The image can be either color or grayscale if it is written as follows.

Pillow (PIL): Get image size (width, height) with sizewidthheight

PIL.Image object obtained by reading an image with Pillow (PIL) has attributes sizewidth, and height.

size is a (width, height) tuple.

The width and height can also be acquired with the attributes width and height.

Grayscale (monochrome) images can be processed in the same way.

Source: https://note.nkmk.me/en/python-opencv-pillow-image-size/

Leave a Comment