使用 Python、OpenCV 和 Pillow(PIL) 獲取圖像大小(寬度和高度)

商業

在 Python 中有幾個用於處理圖像的庫,例如 OpenCV 和 Pillow (PIL)。本節說明如何獲取每個圖像的大小(寬度和高度)。

您可以使用 OpenCV 的形狀和 Pillow 的大小 (PIL) 將圖像大小(寬度和高度)作為元組獲取,但請注意,每個的順序是不同的。

此處提供了以下信息。

  • OpenCV
    • ndarray.shape獲取圖片尺寸(寬、高)
      • 對於彩色圖像
      • 對於灰度(單色)圖像
  • Pillow(PIL)
    • size,width,height獲取圖片尺寸(寬、高)

有關如何獲取文件大小(容量)而不是圖像大小(大小)的信息,請參閱以下文章。

OpenCV:ndarray.shape:獲取圖片尺寸(寬、高)

在 OpenCV 中加載圖像文件時,將其視為 NumPy 數組 ndarray,可以從屬性 shape 中獲取圖像的大小(寬度和高度),該屬性表示 ndarray 的形狀。

不僅在 OpenCV 中,當在 Pillow 中加載圖像文件並轉換為 ndarray 時,使用 shape 獲得 ndarray 表示的圖像的大小。

對於彩色圖像

在彩色圖像的情況下,使用以下三維 ndarray。

  • 行(高)
  • 行(寬度)
  • 顏色 (3)

shape 是上述元素的元組。

import cv2

im = cv2.imread('data/src/lena.jpg')

print(type(im))
# <class 'numpy.ndarray'>

print(im.shape)
print(type(im.shape))
# (225, 400, 3)
# <class 'tuple'>

要將每個值分配給變量,請按如下方式解壓縮元組。

h, w, c = im.shape
print('width:  ', w)
print('height: ', h)
print('channel:', c)
# width:   400
# height:  225
# channel: 3

_
當解包一個元組時,上面的內容可以按照慣例被分配為一個變量,用於以後將不會使用的值。例如,如果不使用顏色數(通道數),則使用以下內容。

h, w, _ = im.shape
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

它也可以通過索引(索引)指定它而不將其分配給變量來按原樣使用。

print('width: ', im.shape[1])
print('height:', im.shape[0])
# width:  400
# height: 225

(width, height)
如果你想得到這個元組,你可以使用 slice 並編寫以下內容:cv2.resize() 等。如果你想通過大小指定參數,使用這個。

print(im.shape[1::-1])
# (400, 225)

對於灰度(單色)圖像

在灰度(單色)圖像的情況下,使用以下二維 ndarray。

  • 行(高)
  • 行(寬度)

形狀將是這個元組。

im_gray = cv2.imread('data/src/lena.jpg', cv2.IMREAD_GRAYSCALE)

print(im_gray.shape)
print(type(im_gray.shape))
# (225, 400)
# <class 'tuple'>

與彩色圖像基本相同。

h, w = im_gray.shape
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

print('width: ', im_gray.shape[1])
print('height:', im_gray.shape[0])
# width:  400
# height: 225

如果要將寬度和高度分配給變量,無論圖像是彩色還是灰度,都可以按如下方式進行。

h, w = im.shape[0], im.shape[1]
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

(width, height)
如果你想得到這個元組,你可以使用切片,寫成如下。無論圖像是彩色還是灰度,都可以使用以下書寫風格。

print(im_gray.shape[::-1])
print(im_gray.shape[1::-1])
# (400, 225)
# (400, 225)

Pillow(PIL):size, width, height:獲取圖片尺寸(寬、高)

使用 Pillow(PIL) 讀取圖像獲得的圖像對象具有以下屬性。

  • size
  • width
  • height

大小是以下元組。
(width, height)

from PIL import Image

im = Image.open('data/src/lena.jpg')

print(im.size)
print(type(im.size))
# (400, 225)
# <class 'tuple'>

w, h = im.size
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

您還可以分別獲取寬度和高度作為屬性。
width,height

print('width: ', im.width)
print('height:', im.height)
# width:  400
# height: 225

灰度(單色)圖像也是如此。

im_gray = Image.open('data/src/lena.jpg').convert('L')

print(im.size)
print('width: ', im.width)
print('height:', im.height)
# (400, 225)
# width:  400
# height: 225
Copied title and URL