如何在OpenCV中获取图像的宽度和高度?

83

我想获取图像的宽度和高度,在OpenCV中该如何实现?

例如:

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

这是正确的吗?


请具体说明编程语言,因为有些东西在某些语言中有效,而在其他语言中则无效。 - CristiFati
2个回答

128

您可以使用rowscols属性:

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

或者size()

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

或者size

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

103

同时,在Python中使用openCV,你可以这样做:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

7
好的,但是OP正在寻求C++方面的帮助。 - Petruza
72
是的,这是真实的,但在谷歌搜索Python版本时,会将您带到这里。 - Anoroah
3
属性错误:'NoneType'对象没有属性'shape'。 - Arshdeep Singh
@ArshdeepSingh 确保图像存在,图像路径正确,您正在正确读取它,并且 img 对象的类型为 <class 'numpy.ndarray'>。如果图像路径不正确并且您尝试在 cv2.imread 中使用它,它会给出一个警告而不是错误。您的程序不会在那里停止! - Milan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接