pythonimageopencvnumpy

Python OpenCV2 (cv2) wrapper to get image size?


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?


Solution

  • 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