140

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?

Joel G
  • 25
  • 2
  • 7
xercool
  • 4,179
  • 6
  • 27
  • 33

3 Answers3

299

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

djwbrown
  • 1,091
  • 1
  • 11
  • 15
jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
  • 37
    Oh, come on. Instead of assuming that the image will be BGR or mono, just write generally - `h, w = img.shape[:2]`, especially as the OP is not interested in the depth. (Neither was I). See my answer for more details. – Tomasz Gandor Jan 09 '15 at 23:46
  • 2
    I found this helpful: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html#accessing-image-properties – djwbrown Jun 13 '15 at 18:48
  • 1
    If you're only interested in height and width, a more pythonic alternative to @TomaszGandor's comment would be ```python h, w, _ = img.shape ``` – Zenahr Jul 30 '21 at 20:41
  • `h, w, *_ = img.shape` – fferri Apr 09 '22 at 11:00
28

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 :)

Tomasz Gandor
  • 8,235
  • 2
  • 60
  • 55
0
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()

yuanzz
  • 1,359
  • 12
  • 15