Python Pillow - 浮雕影像



一般來說,浮雕用於在紙張或卡片上建立凸起的浮雕影像以達到三維效果,在 19 世紀,英國郵政服務就曾廣泛使用這種工藝為郵票增添優雅氣息。此過程涉及凸起影像、設計或文字的某些部分,以建立三維效果。

在影像處理和計算機圖形學中,影像浮雕是一種技術,其中影像中的每個畫素都會根據原始影像的明暗邊界轉換為高光或陰影版本。對比度低的區域將替換為灰色背景。生成的浮雕影像有效地表示原始影像中每個位置的顏色變化率。將浮雕濾鏡應用於影像通常會產生類似於紙張或金屬浮雕的原始影像的輸出,因此得名。

Python 的 Pillow 庫在 ImageFilter 模組中提供了幾個標準影像濾鏡,可以透過呼叫 image.filter() 方法對影像執行不同的濾鏡操作。在本教程中,我們將瞭解 ImageFilter 模組提供的浮雕濾鏡的工作原理。

使用 Image.filter() 方法應用 ImageFilter.EMBOSS 核心濾鏡

ImageFilter.EMBOSS 濾鏡是 Pillow 庫當前版本中提供的內建濾鏡選項之一,用於在影像中建立浮雕效果。

以下是應用影像浮雕的步驟:

  • 使用 Image.open() 函式載入輸入影像。

  • 將 filter() 函式應用於載入的 Image 物件,並將 ImageFilter.EMBOSS 作為函式的引數提供。該函式將返回浮雕影像作為 PIL.Image.Image 物件。

示例

這是一個使用 Image.filter() 方法和 ImageFilter.EMBOSS 核心濾鏡的示例。

from PIL import Image, ImageFilter

# Load an input image
input_image = Image.open("Images/TP logo.jpg")

# Apply an emboss effect to the image
embossed_result = input_image.filter(ImageFilter.EMBOSS)

# Display the input image
input_image.show()

# Display the modified image with the emboss effect
embossed_result.show()

輸入影像

tp logo

輸出影像

帶有浮雕效果的輸出濾鏡影像:

imagefilter emboss

自定義 EMBOSS 濾鏡以向浮雕影像新增深度和方位角

在 Pillow 庫的原始碼中,我們可以在“ImageFilter.py”模組中觀察到 EMBOSS 類。此類表示浮雕濾鏡,並提供了一種建立影像浮雕效果的基本方法。

# Embossing filter.
class EMBOSS(BuiltinFilter):
   name = "Emboss"
   # fmt: off
   filterargs = (3, 3), 1, 128, (
      -1, 0, 0,
      0,  1, 0,
      0,  0, 0,
   )

該濾鏡透過逐畫素將矩陣應用於影像來操作。矩陣包含確定應用於每個畫素的變換的值。透過修改矩陣,您可以控制浮雕效果的方位角和強度。

矩陣是一個 3x3 網格,其中每個元素對應於當前畫素及其周圍畫素。中心值表示正在處理的當前畫素。該濾鏡根據矩陣中它們的權重組合這些值以建立變換後的畫素。您可以透過調整縮放和偏移引數來自定義濾鏡,這些引數會影響效果的整體強度。

示例

以下是一個演示如何將自定義浮雕濾鏡應用於影像的示例,允許您透過調整各種引數來控制浮雕效果的外觀。

from PIL import Image, ImageFilter

# Open the input image 
image = Image.open('Images/TP logo.jpg')

# modify the filterargs such as scale, offset and the matrix
ImageFilter.EMBOSS.filterargs=((3, 3), 2, 150, (0, 0, 0, 0, 1, 0, -2, 0, 0))
    
# Apply an emboss effect to the image
embossed_result = image.filter(ImageFilter.EMBOSS)

# Display the input image
image.show()

# Display the modified image with the emboss effect
embossed_result.show()

輸入影像

tp logo

輸出影像

帶有自定義浮雕效果的輸出濾鏡影像:

emboss effect
廣告