74

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
  • 131,796
  • 23
  • 122
  • 195
sarmad m
  • 781
  • 1
  • 6
  • 5

2 Answers2

114

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
  • 39,217
  • 13
  • 114
  • 193
91

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 
Anoroah
  • 1,767
  • 1
  • 18
  • 29
  • 6
    Good, but OP is asking for C++ – Petruza Mar 08 '18 at 21:28
  • 62
    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