Matplotlib - 影像縮圖



縮圖是原始影像的較小且壓縮版本,是各種應用程式中必不可少的元件,包括影像預覽、Web 開發以及最佳化包含大量影像的網頁和應用程式的載入速度。

在本教程中,我們將探討如何使用 Matplotlib 有效地生成影像縮圖。Matplotlib 利用Python Pillow 庫進行影像處理,並允許我們輕鬆地從現有影像生成縮圖。

Matplotlib 中的影像縮圖

Matplotlib 在其影像模組中提供了thumbnail()函式來生成具有可自定義引數的縮圖,允許使用者有效地為各種目的建立縮小版的影像。

以下是函式的語法:

語法

matplotlib.image.thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', preview=False)

以下是其引數的詳細資訊:

  • infile - 輸入影像檔案。如您所知,Matplotlib 依賴 Pillow 讀取影像,因此它支援各種檔案格式,包括 PNG、JPG、TIFF 等。

  • thumbfile - 將儲存縮圖的檔名或類檔案物件。

  • scale - 縮圖的縮放因子。它確定縮圖相對於原始影像的大小縮減。較小的縮放因子會生成較小的縮圖。

  • interpolation - 重取樣過程中使用的插值方案。此引數指定用於估計縮圖中畫素值的方法。

  • preview - 如果設定為 True,則將使用預設後端(可能是使用者介面後端),如果呼叫 show(),則可能會彈出一個圖形。如果設定為 False,則使用 FigureCanvasBase 建立圖形,並且選擇 Figure.savefig 通常會選擇的繪圖後端。

該函式返回包含縮圖的 Figure 例項。此 Figure 物件可以根據需要進一步操作或儲存。

為單個影像生成縮圖

Matplotlib 支援 png、pdf、ps、eps svg 等各種影像格式,使其適用於不同的用例。

示例

這是一個為單個 .jpg 影像建立縮圖的示例。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

input_image_path = "Images/Tajmahal.jpg"
output_thumbnail_path = "Images/Tajmahal_thumbnail.jpg"

# Load the original image
img = mpimg.imread(input_image_path)

# Create a thumbnail using Matplotlib
thumb = mpimg.thumbnail(input_image_path, output_thumbnail_path, scale=0.15)

print(f"Thumbnail generated for {input_image_path}. Saved to {output_thumbnail_path}")

輸出

如果您訪問儲存影像的資料夾,您可以觀察到原始影像和輸出縮圖影像,如下所示:

image_thumbnail_ex1

為多個影像生成縮圖

考慮這樣一個場景:您在一個目錄中有多個影像,並且您希望為每個影像生成縮圖。

示例

這是一個在目錄中建立多個 PNG 影像的縮圖的示例。將以下指令碼另存為 generate_thumbnails.py 檔案。

from argparse import ArgumentParser
from pathlib import Path
import sys
import matplotlib.image as image

parser = ArgumentParser(description="Generate thumbnails of PNG images in a directory.")
parser.add_argument("imagedir", type=Path)
args = parser.parse_args()

if not args.imagedir.is_dir():
   sys.exit(f"Could not find the input directory {args.imagedir}")

outdir = Path("thumbs")
outdir.mkdir(parents=True, exist_ok=True)
for path in args.imagedir.glob("*.png"):
   outpath = outdir / path.name
   try:
      fig = image.thumbnail(path, outpath, scale=0.15)
      print(f"Saved thumbnail of {path} to {outpath}")
   except Exception as e:
      print(f"Error generating thumbnail for {path}: {e}")

然後在命令提示符中按如下方式執行指令碼

python generate_thumbnails.py /path/to/all_images

輸出

執行上述程式後,將建立一個名為“thumbs”的目錄,併為工作目錄中的 PNG 影像生成縮圖。如果遇到格式不同的影像,它將列印錯誤訊息並繼續處理其他影像。

Saved thumbnail of Images\3d_Star.png to thumbs\3d_Star.png
Saved thumbnail of Images\balloons_noisy.png to thumbs\balloons_noisy.png
Saved thumbnail of Images\binary image.png to thumbs\binary image.png
Saved thumbnail of Images\black and white.png to thumbs\black and white.png
Saved thumbnail of Images\Black1.png to thumbs\Black1.png
Saved thumbnail of Images\Blank.png to thumbs\Blank.png
Saved thumbnail of Images\Blank_img.png to thumbs\Blank_img.png
Saved thumbnail of Images\Circle1.png to thumbs\Circle1.png
Saved thumbnail of Images\ColorDots.png to thumbs\ColorDots.png
Saved thumbnail of Images\colorful-shapes.png to thumbs\colorful-shapes.png
Saved thumbnail of Images\dark_img1.png to thumbs\dark_img1.png
Saved thumbnail of Images\dark_img2.png to thumbs\dark_img2.png
Saved thumbnail of Images\decore.png to thumbs\decore.png
Saved thumbnail of Images\deform.png to thumbs\deform.png
Saved thumbnail of Images\Different shapes.png to thumbs\Different shapes.png
Error generating thumbnail for Images\Different shapes_1.png: not a PNG file
Saved thumbnail of Images\Ellipses.png to thumbs\Ellipses.png
Error generating thumbnail for Images\Ellipses_and_circles.png: not a PNG file
Saved thumbnail of Images\images (1).png to thumbs\images (1).png
Saved thumbnail of Images\images (3).png to thumbs\images (3).png
Saved thumbnail of Images\images.png to thumbs\images.png
Saved thumbnail of Images\image___1.png to thumbs\image___1.png
Saved thumbnail of Images\Lenna.png to thumbs\Lenna.png
Saved thumbnail of Images\logo-footer-b.png to thumbs\logo-footer-b.png
Saved thumbnail of Images\logo-w.png to thumbs\logo-w.png
Saved thumbnail of Images\logo.png to thumbs\logo.png
Saved thumbnail of Images\logo_Black.png to thumbs\logo_Black.png
廣告