如何在 OpenCV 中使用 Python 訪問影像屬性?
在OpenCV中,影像是一個NumPy陣列。我們可以使用 NumPy 陣列的屬性來訪問影像屬性。對於輸入影像img,我們訪問以下影像屬性 -
影像型別 - 影像的資料結構。OpenCV 中的影像是 numpy.ndarray。我們可以將其訪問為type(img)。
影像形狀 - 它以[H, W, C]格式表示形狀,其中H、W和C分別表示影像的高度、寬度和通道數。我們可以將其訪問為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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP