图像大小(Python,OpenCV)

54

我想在Python中获取图像大小,就像在C++中那样。

int w = src->width;
printf("%d", 'w');

-> 这个语法是干什么用的?我以前从来没见过... - Yatharth Agarwal
访问对象的属性就像在PHP中一样吗?如果是这样,为什么他们不只使用点运算符(.)呢? - Yatharth Agarwal
@YatharthROCK 在C++中,a->b等同于(*a).b - Gabi Purcaru
@GabiPurcaru 好的,那么 * 操作符是做什么用的呢?在 Python 中它可以打开元组或列表... - Yatharth Agarwal
我不知道它的技术名称,但它可以将指针(甚至不要问那是什么!)转换为其所指向的东西。 - Gabi Purcaru
2
这被称为解引用,并允许我们通过*操作符访问指向变量的值。 - Samuele Mattiuzzo
8个回答

151

使用openCV和numpy很容易,像这样:

import cv2

img = cv2.imread('path/to/img',0)
height, width = img.shape[:2]

13
为什么需要导入numpy来实现这个? - virtualxtc
2
它在内部使用numpy。 - Nikhil Pareek

29

对我来说,最简单的方法是获取image.shape返回的所有值:

height, width, channels = img.shape

如果您不想要通道数(用于确定图像是BGR还是灰度图像),只需删除该值即可:

如果您不需要通道数,则可以删除该值。
height, width, _ = img.shape

22

使用模块 cv 中的函数 GetSize,并将您的图像作为参数传递。它会返回一个包含两个元素(宽度和高度)的元组:

width, height = cv.GetSize(src)

13
这个函数似乎在OpenCV 3中不存在。也许一段时间以前它被移除了? - polm23
2
链接似乎已经失效。 - Manuel V. Battan
这个函数似乎已经被废弃了。 - MertTheGreat

18

我使用numpy.size()来实现相同的功能:

import numpy as np
import cv2

image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)

4
从这个教程中:https://www.tutorialkart.com/opencv/python/opencv-python-get-image-size/
import cv2

# read image
img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED)

# get dimensions of image
dimensions = img.shape

# height, width, number of channels in image

height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]

来自另一个教程: https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/

image = cv2.imread("jp.png")

(h, w, d) = image.shape

请在发布答案之前仔细检查。


2
这是一个返回图片尺寸的方法:
from PIL import Image
import os

def get_image_dimensions(imagefile):
    """
    Helper function that returns the image dimentions

    :param: imagefile str (path to image)
    :return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
    """
    # Inline import for PIL because it is not a common library
    with Image.open(imagefile) as img:
        # Calculate the width and hight of an image
        width, height = img.size

    # calculat ethe size in bytes
    size_bytes = os.path.getsize(imagefile)

    return dict(width=width, height=height, size_bytes=size_bytes)

0

我相信只需要 img.shape[-1::-1] 就更好了。


0

您可以使用image.shape来获取图像的尺寸。它返回3个值。第一个值是图像的高度,第二个是宽度,最后一个是通道数。在这里您不需要最后一个值,因此可以使用以下代码获取图像的高度和宽度:

height, width = src.shape[:2]
print(width, height)

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