AppDividend
Latest Code Tutorials

Python cv2 Image Size: How to Get Image Size in Python

0

Python cv2 module uses the numpy library to manipulate the images. Here one thing to note that I am assuming that you are working with BGR images.

Python cv2 Image Size

To get the proper size of an image, use numpy.shape property. In OpenCV, we can get the image size (width, height) as a tuple with the attribute shape of ndarray.

To get the image size (width, height) with OpenCV, use the ndarray.shape. It works on the following kind of image.

  1. For color image
  2. For grayscale (monochrome) images

For color Image

Let’s talk about the color image. In the case of a color image, it is a 3D ndarray of row (height) x column (width) x color (3). The shape is a tuple of (row (height), column (width), color (3)).

# Importing cv2
import cv2

# Path
img = cv2.imread('data.jpg')

# <class 'numpy.ndarray'>
print(img.shape)

Output

(4000, 3000, 3)

You can see that we get the tuple containing height, width, and color. We can assign each value to a variable, unpack the tuple as follows.

# app.py

# Importing cv2
import cv2

# Image
img = cv2.imread('data.jpg')

h, w, c = img.shape
print('width:  ', w)
print('height: ', h)
print('channel:', c)

Output

width:   3000
height:  4000
channel: 3

When unpacking the tuple, values that are not used after that may be assigned to _(underscore) by convention. See the following code.

# Importing cv2
import cv2

# Image
img = cv2.imread('data.jpg')

h, w, _ = img.shape
print('width:  ', w)
print('height: ', h)

You can also use an index to access the width and height of the img variable.

# Importing cv2
import cv2

# Image
img = cv2.imread('data.jpg')

print('width:  ', img.shape[0])
print('height: ', img.shape[1])

Output

width:   4000
height:  3000

When we are resetting the size of an image using the cv2.resize() method, it needs to be (width, height).

For Grayscale Image

When you are working with grayscale (monochrome) images, it is a 2D ndarray of rows (height) x columns (width). The shape is a tuple of (row (height), column (width)).

# Importing cv2
import cv2

# Image
img = cv2.imread('grayimage.jpg', cv2.IMREAD_GRAYSCALE)

print(img.shape)

Output

(6000, 4000)

The unpacking tuple is the same as the color image, and also we can access the image width and height using the index.

# Importing cv2
import cv2

# Image
img = cv2.imread('grayimage.jpg', cv2.IMREAD_GRAYSCALE)

h, w = img.shape
print('width: ', w)
print('height:', h)

# Accessing using index
print('Accessing width and height using index')
print('width: ', img.shape[1])
print('height:', img.shape[0])

Output

width:  4000
height: 6000
Accessing width and height using index
width:  4000
height: 6000

That is it for Python cv2 image size. To obtain the size of the image, use numpy.shape() method.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.