如何在 Python 中根據影像尺寸屬性過濾影像?


Python 提供了多個用於影像處理的庫,包括 Pillow、Python 影像庫、scikit-image 或 OpenCV。

我們將在這裡使用 Pillow 庫進行影像處理,因為它提供了多個用於影像操作的標準程式,並支援各種影像檔案格式,如 jpeg、png、gif、tiff、bmp 等。

Pillow 庫構建在 Python 影像庫 (PIL) 之上,並提供了比其父庫 (PIL) 更多的功能。

安裝

我們可以使用 pip 安裝 pillow,只需在命令終端中輸入以下內容:

$ pip install pillow

Pillow 的基本操作

讓我們使用 pillow 庫對影像進行一些基本操作。

from PIL import Image
image = Image.open(r"C:\Users\rajesh\Desktop\imagefolder\beach-parga.jpg")
image.show()
# The file format of the source file.
# Output: JPEG
print(image.format)

# The pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.”
# Output: RGB
print(image.mode)

# Image size, in pixels. The size is given as a 2-tuple (width, height).
# Output: (2048, 1365)
print(image.size)


# Colour palette table, if any.
#Output: None
print(image.palette)

輸出

JPEG
RGB
(2048, 1365)
None

根據尺寸過濾影像

下面的程式將減小特定路徑(預設路徑:當前工作目錄)中所有影像的大小。我們可以在下面給出的程式中更改影像的最大高度、最大寬度或副檔名。

程式碼

import os
from PIL import Image

max_height = 900
max_width = 900
extensions = ['JPG']

path = os.path.abspath(".")
def adjusted_size(width,height):
   if width > max_width or height>max_height:
      if width > height:
         return max_width, int (max_width * height/ width)
      else:
         return int (max_height*width/height), max_height
   else:
      return width,height

if __name__ == "__main__":
   for img in os.listdir(path):
      if os.path.isfile(os.path.join(path,img)):
         img_text, img_ext= os.path.splitext(img)
         img_ext= img_ext[1:].upper()
         if img_ext in extensions:
            print (img)
            image = Image.open(os.path.join(path,img))
            width, height= image.size
            image = image.resize(adjusted_size(width, height))
            image.save(os.path.join(path,img))

輸出

another_Bike.jpg
clock.JPG
myBike.jpg
Top-bike-wallpaper.jpg

執行以上指令碼後,當前工作目錄(當前為 Python 指令碼資料夾)中存在的影像將具有 900(寬度/高度)的最大尺寸。

更新於: 2019-07-30

230 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告