Python Pillow - 新增影像填充



新增影像填充是指在影像周圍新增邊框。這是一種在調整影像大小而不改變其縱橫比或裁剪影像的有用技術。可以在影像的頂部、底部、左側和右側新增填充。這在處理邊緣具有重要資訊的影像時尤其重要,您希望保留這些資訊以進行分割等任務。

Pillow (PIL) 庫在其 ImageOps 模組中提供了兩個函式,pad()expand(),用於向影像新增填充。

使用 ImageOps.pad() 函式填充影像

pad() 函式用於將影像調整大小並填充到指定的大小和縱橫比。它允許您指定輸出大小、重取樣方法、背景顏色以及原始影像在填充區域中的位置。該函式的語法如下:

PIL.ImageOps.pad(image, size, method=Resampling.BICUBIC, color=None, centering=(0.5, 0.5))

其中:

  • image - 要調整大小和填充的影像。

  • size - 一個元組,指定請求的輸出大小(以畫素為單位),格式為 (寬度, 高度)。該函式將調整影像大小到此尺寸,同時保持縱橫比。

  • method - 此引數確定調整大小期間使用的重取樣方法。預設方法是 BICUBIC,這是一種插值型別。您可以指定 PIL 支援的其他重取樣方法。常見的選項包括 NEAREST、BILINEAR 和 LANCZOS。

  • color - 此引數指定填充區域的背景顏色。它也支援 RGBA 元組,例如 (R, G, B, A)。如果未指定,則預設背景顏色為黑色。

  • centering - 此引數控制原始影像在填充版本中的位置。它指定為一個包含 0 到 1 之間兩個值的元組。

示例

這是一個使用 ImageOps.pad() 函式向影像新增填充的示例。

from PIL import Image
from PIL import ImageOps

# Open the input image
input_image = Image.open('Images/elephant.jpg')

# Add padding to the image
image_with_padding = ImageOps.pad(input_image, (700, 300), color=(130, 200, 230))

# Display the input image
input_image.show()

# Display the image with the padding
image_with_padding.show()

輸入

elephant

輸出

新增填充後調整大小後的輸出影像:

elephant resize

使用 ImageOps.expand() 函式新增邊框

expand() 函式在影像周圍新增指定寬度和顏色的邊框。它可用於建立裝飾性框架或強調影像內容。其語法如下:

PIL.ImageOps.expand(image, border=0, fill=0)
  • image - 要擴充套件邊框的影像。

  • border - 要新增的邊框寬度(以畫素為單位)。它決定影像周圍邊框的寬度。預設值為 (0)。

  • fill - 畫素填充值,表示邊框的顏色。預設值為 0,對應於黑色。您可以使用適當的顏色值指定填充顏色。

示例

這是一個使用 ImageOps.expand() 函式向影像新增填充的示例。

from PIL import Image, ImageOps

# Open the input image
input_image = Image.open('Images/Car_2.jpg')

# Add padding of 15-pixel border
image_with_padding = ImageOps.expand(input_image, border=(15, 15, 15, 15), fill=(255, 180, 0))

# Display the input image
input_image.show()

# Display the output image with padding
image_with_padding.show()

輸入

yellow car

輸出

新增填充後的輸出影像:

car border
廣告