问题:Python OpenCV2(cv2)包装器获取图像大小?

如何cv2在Python OpenCV(numpy)的包装器中获取图像的大小。除了之外还有其他正确的方法吗numpy.shape()?如何获得以下格式的尺寸:(宽度,高度)列表?

How to get the size of an image in cv2 wrapper 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?


回答 0

cv2numpy用于处理图像,因此使用来获取图像大小的正确和最佳方法是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

如果您正在使用二进制图像,img它将具有两个尺寸,因此必须将代码更改为:height, width = img.shape

cv2 uses numpy for 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:

>>> 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, img will have two dimensions, and therefore you must change the code to: height, width = img.shape


回答 1

恐怕没有“更好”的方法来获得这种大小,但是没有那么多痛苦。

当然,您的代码对于二进制/单图像以及多通道图像都应该是安全的,但是图像的主要尺寸始终以numpy数组的形状排在首位。如果您选择可读性,或者不想打扰它,可以将其包装在一个函数中,并为其命名,例如cv_size

import numpy as np
import cv2

# ...

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

如果您在终端机/ ipython上,还可以使用lambda表示它:

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

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

编辑

本来我以为可以使用[:2],但是numpy的形状是(height, width[, depth]),并且我们需要(width, height)cv2.resize预期的那样-因此我们必须使用[1::-1]。难忘的是[:2]。还有谁记得反向切片?

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:

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:

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

Writing functions with def is not fun while working interactively.

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.resize expects, so – we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。