84

I want to get image width and height, how can I do that in OpenCV?

For example:

Mat src = imread("path_to_image");
cout << src.width;

Is that right?

1
  • Please be specific about languages. Because some things work in some but not in others.
    – CristiFati
    Aug 31, 2022 at 9:05

2 Answers 2

129

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

or size

cout << "Width : " << src.size[1] << endl;
cout << "Height: " << src.size[0] << endl;
105

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 
4
  • 7
    Good, but OP is asking for C++
    – Petruza
    Mar 8, 2018 at 21:28
  • 73
    Yes this is true but the google search for the python one brings you here.
    – Anoroah
    Mar 8, 2018 at 23:33
  • 3
    AttributeError: 'NoneType' object has no attribute 'shape' Oct 24, 2018 at 17:28
  • @ArshdeepSingh make sure the image exists, the image path is correct, you are reading it properly, and the img object is of type <class 'numpy.ndarray'>. If the image path is incorrect and you try to use that in cv2.imread, it would give a WARNING not an error. Your program won't stop there!
    – Milan
    Mar 23, 2022 at 18:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.