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?