83

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?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
sarmad m
  • 879
  • 1
  • 7
  • 5

2 Answers2

128

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;
Miki
  • 40,887
  • 13
  • 123
  • 202
102

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 
Anoroah
  • 1,987
  • 2
  • 20
  • 31
  • 7
    Good, but OP is asking for C++ – Petruza Mar 08 '18 at 21:28
  • 71
    Yes this is true but the google search for the python one brings you here. – Anoroah Mar 08 '18 at 23:33
  • 3
    AttributeError: 'NoneType' object has no attribute 'shape' – Arshdeep Singh Oct 24 '18 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 ``. 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 '22 at 18:11