Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python OpenCV2 (cv2) wrapper to get image size?

People also ask

How do I get the size of an image in Python?

open() is used to open the image and then . width and . height property of Image are used to get the height and width of the image.

How do you find the height and width of an image in cv2?

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.

How do you extract the height and weight of an image using OpenCV?

When working with OpenCV Python, images are stored in numpy ndarray. To get the image shape or size, use ndarray. shape to get the dimensions of the image. Then, you can use index on the dimensions variable to get width, height and number of channels for each pixel.

How do I find the resolution of an image in OpenCV?

there is no way to do that with opencv. and resolution is a dtp thing, it's irrelevant in computer-vision. As @berak says, the resolution is largely irrelevant until you actually come to lay down the pixels on a piece of paper or a screen.


cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape


I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?