Python OpenCV2 (cv2) wrapper to get image size?

PythonImageOpencvNumpy

Python Problem Overview


How to get the size of an image in cv2 wrapper in Python OpenCV (numpy). Is there a correct way to do that other than numpy.shape(). How can I get it in these format dimensions: (width, height) list?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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?

Python 3 tuple unpacking

After we all moved to Python 3, and thus have this https://peps.python.org/pep-3132/ -- we can also get h and w by using tuple unpacking:

h, w, *_ = img.shape

This time, we need not worry about single channel images :)

Solution 3 - Python

import cv2
import numpy as np

def main():
    # init cv
    cap = cv2.VideoCapture(0)

    while True:
        success, img = cap.read()
# WAY 1
        img = cv2.flip(img, 1)

        print(img.shape)
# WAY 2
        print(
            f"width: {cap.get(cv2.CAP_PROP_FRAME_WIDTH)}, height: {cap.get(cv2.CAP_PROP_FRAME_HEIGHT)}, fps: {cap.get(cv2.CAP_PROP_FPS)}")
        cv2.imshow(winname="universal control", mat=img)
        cv2.waitKey(1)


if __name__ == '__main__':
    main()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxercoolView Question on Stackoverflow
Solution 1 - PythonjabaldonedoView Answer on Stackoverflow
Solution 2 - PythonTomasz GandorView Answer on Stackoverflow
Solution 3 - PythonyuanzzView Answer on Stackoverflow