Python OpenCV2(cv2)包装器来获取图像大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19098104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:51:22  来源:igfitidea点击:

Python OpenCV2 (cv2) wrapper to get image size?

pythonimageopencvnumpy

提问by xercool

How to get the size of an image in cv2wrapper in Python OpenCV (numpy). Is there a correct way to do that other than numpy.shape(). How can I get it in these format dimensions: (width, height) list?

如何cv2在 Python OpenCV (numpy) 的包装器中获取图像的大小。除了numpy.shape(). 如何以这些格式尺寸获取它:(宽度,高度)列表?

采纳答案by jabaldonedo

cv2uses numpyfor manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

cv2用途numpy用于处理图像,所以正确的和最佳的方式来获得图像的大小使用numpy.shape。假设您正在使用 BGR 图像,以下是一个示例:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, imgwill have two dimensions, and therefore you must change the code to: height, width = img.shape

如果您使用的是二进制图像,img将有两个维度,因此您必须将代码更改为:height, width = img.shape

回答by Tomasz Gandor

I'm afraid there is no "better" way to get this size, however it's not that much pain.

恐怕没有“更好”的方法来获得这个尺寸,但这并没有那么痛苦。

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

当然,您的代码对于二进制/单声道图像以及多通道图像都应该是安全的,但是图像的主要维度始终在 numpy 数组的形状中排在第一位。如果您选择可读性,或者不想打扰输入这个,您可以将它包装在一个函数中,并给它一个您喜欢的名称,例如cv_size

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

如果你在终端/ipython 上,你也可以用 lambda 来表达它:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with defis not fun while working interactively.

def在交互工作时使用 with 编写函数并不有趣。

Edit

编辑

Originally I thought that using [:2]was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resizeexpects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

最初我认为 using[:2]是可以的,但是 numpy 形状是(height, width[, depth]),我们需要(width, height),正如所cv2.resize期望的那样 - 我们必须使用[1::-1]. 甚至不如[:2]. 谁还记得反向切片?