如何在 OpenCV 中使用 Python 访问图像属性?


OpenCV中,图像是一个NumPy数组。我们可以使用 NumPy 数组的属性来访问图像属性。对于输入图像img,我们访问以下图像属性 -

  • 图像类型 - 图像的数据结构。OpenCV 中的图像是 numpy.ndarray。我们可以将其访问为type(img)

  • 图像形状 - 它以[H, W, C]格式表示形状,其中H、WC分别表示图像的高度、宽度通道数。我们可以将其访问为img.shape

  • 图像大小 - 它是图像中像素的总数。它也是数组中元素的总数。我们可以将其访问为img.size

  • 数据类型 - 它是图像数组元素的 dtype。我们可以将其访问为img.dtype

  • 维度 - 图像的维度。彩色图像具有 3 个维度(高度、宽度和通道),而灰度图像具有 2 个维度(只有高度和宽度)。我们可以将其访问为img.ndim

  • 像素值 - 像素值是范围在 0 到 255 之间的无符号整数。我们可以直接访问这些值,例如print(img)

让我们来看一些 Python 程序,以访问图像的属性。

输入图像

我们将在以下示例中使用此图像作为输入文件。

示例 1

在此程序中,我们将访问给定彩色图像的图像属性。

import cv2 # read the input image img = cv2.imread('cat.jpg') # image properties print("Type:",type(img)) print("Shape of Image:", img.shape) print('Total Number of pixels:', img.size) print("Image data type:", img.dtype) # print("Pixel Values:\n", img) print("Dimension:", img.ndim)

输出

运行此程序时,将产生以下输出 -

Type: <class 'numpy.ndarray'=""> 
Shape of Image: (700, 700, 3) 
Total Number of pixels: 1470000 
Image data type: uint8 
Dimension: 3

让我们看另一个例子。

示例 2

在此程序中,我们将访问灰度图像的图像属性。

import cv2 # read the input image img = cv2.imread('cat.jpg', 0) # image properties print("Type:",type(img)) print("Shape of Image:", img.shape) print('Total Number of pixels:', img.size) print("Image data type:", img.dtype) print("Pixel Values:\n", img) print("Dimension:", img.ndim)

输出

运行以上 Python 程序时,将产生以下输出 -

Type: <class 'numpy.ndarray'> 
Shape of Image: (700, 700) 
Total Number of pixels: 490000 
Image data type: uint8 
Pixel Values:
   [[ 92 92 92 ... 90 90 90]
   [ 92 92 92 ... 90 90 90] 
   [ 92 92 92 ... 90 90 90] 
   ... 
   [125 125 125 ... 122 122 121] 
   [126 126 126 ... 122 122 122] 
   [126 126 126 ... 123 123 122]] 
Dimension: 2

更新于: 2022年9月27日

3K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.