如何检查numpy数组的尺寸?

The*_*ank 2 python numpy image

我想在函数中做这样的事情:

if image.shape == 2 dimensions
    return image # this image is grayscale
else if image.shape = 3 dimensions
    return image # image is either RGB or YCbCr colorspace
Run Code Online (Sandbox Code Playgroud)

这里,图像是一个numpy数组.我无法定义检查条件.我真的陷入了困境.有人可以帮忙吗?

Rag*_*elt 8

numpy.array.shape是数组维度的元组.您可以计算元组的长度,这将给出维数.

if len(image.shape) == 2:
    return image # this image is grayscale
elif len(image.shape) == 3:
    return image # image is either RGB or YCbCr colorspace
Run Code Online (Sandbox Code Playgroud)

Numpy数组也有一个ndim属性.

if image.ndim == 2:
    return image # this image is grayscale
elif image.ndim == 3:
    return image # image is either RGB or YCbCr colorspace
Run Code Online (Sandbox Code Playgroud)