54

I would like to get the Image size in python,as I do it with c++.

int w = src->width;
printf("%d", 'w');
Andrea Diaz
  • 1,168
  • 4
  • 13
  • 29

8 Answers8

151

Using openCV and numpy it is as easy as this:

import cv2

img = cv2.imread('path/to/img',0)
height, width = img.shape[:2]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
cowhi
  • 2,165
  • 2
  • 17
  • 21
29

For me the easiest way is to take all the values returned by image.shape:

height, width, channels = img.shape

if you don't want the number of channels (useful to determine if the image is bgr or grayscale) just drop the value:

height, width, _ = img.shape
Stein
  • 719
  • 7
  • 9
22

Use the function GetSize from the module cv with your image as parameter. It returns width, height as a tuple with 2 elements:

width, height = cv.GetSize(src)
halex
  • 16,253
  • 5
  • 58
  • 67
18

I use numpy.size() to do the same:

import numpy as np
import cv2

image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)
Rodrigo Lara
  • 181
  • 1
  • 2
4

from this tutorial: https://www.tutorialkart.com/opencv/python/opencv-python-get-image-size/

import cv2

# read image
img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED)

# get dimensions of image
dimensions = img.shape

# height, width, number of channels in image

height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]

from this other tutorial: https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/

image = cv2.imread("jp.png")

(h, w, d) = image.shape

Please double check things before posting answers.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
Javi
  • 913
  • 2
  • 13
  • 15
1

Here is a method that returns the image dimensions:

from PIL import Image
import os

def get_image_dimensions(imagefile):
    """
    Helper function that returns the image dimentions

    :param: imagefile str (path to image)
    :return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
    """
    # Inline import for PIL because it is not a common library
    with Image.open(imagefile) as img:
        # Calculate the width and hight of an image
        width, height = img.size

    # calculat ethe size in bytes
    size_bytes = os.path.getsize(imagefile)

    return dict(width=width, height=height, size_bytes=size_bytes)
Roei Bahumi
  • 3,433
  • 2
  • 20
  • 19
0

I believe simply img.shape[-1::-1] would be nicer.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
Harrison Wang
  • 146
  • 1
  • 5
0

You can use image.shape to get the dimensions of the image. It returns 3 values. The first value is height of an image, the second is width, and the last one is number of channels. You don't need the last value here so you can use below code to get height and width of image:

height, width = src.shape[:2]
print(width, height)
tripleee
  • 175,061
  • 34
  • 275
  • 318
Vilas
  • 51
  • 4