Python Pillow - 影像混合



影像混合 是將兩張或多張影像組合或混合以建立新影像的過程。一種常見的影像混合方法是使用 alpha 混合。在 alpha 混合中,結果中的每個畫素都是根據輸入影像中相應畫素的加權和計算的。表示透明度的 alpha 通道用作權重因子。

此技術通常用於圖形、影像處理和計算機視覺中,以實現各種視覺效果。

Python Pillow 庫在其 Image 模組中提供 `blend()` 函式來對影像執行混合操作。

`Image.blend()` 函式

此函式提供了一種透過指定混合因子 (alpha) 來在兩張影像之間建立平滑過渡的便捷方法。該函式透過使用常量 alpha 值在兩個輸入影像之間進行插值來建立新影像。插值根據以下公式執行:

out=image1×(1.0−alpha)+image2×alpha

以下是該函式的語法:

PIL.Image.blend(im1, im2, alpha)

其中:

  • im1 - 第一張影像。

  • im2 - 第二張影像。它必須與第一張影像具有相同的模式和大小。

  • alpha - 插值 alpha 係數。如果 alpha 為 0.0,則返回第一張影像的副本。如果 alpha 為 1.0,則返回第二張影像的副本。對 alpha 值沒有限制。如有必要,結果將被裁剪以適合允許的輸出範圍。

示例

讓我們來看一個使用Image.blend() 方法混合兩張影像的基本示例。

from PIL import Image

# Load two images
image1 = Image.open("Images/ColorDots.png")
image2 = Image.open("Images/pillow-logo-w.png")

# Blend the images with alpha = 0.5
result = Image.blend(image1, image2, alpha=0.5)

# Display the input and resultant iamges
image1.show()
image2.show()
result.show()

輸入影像

color dots pillow logo

輸出

resultant images

示例

這是一個演示使用 alpha 值為 2 的 PIL.Image.blend() 的示例。

from PIL import Image

# Load two images
image1 = Image.open("Images/ColorDots.png")
image2 = Image.open("Images/pillow-logo-w.png")

# Blend the images with alpha = 2
result = Image.blend(image1, image2, alpha=2)

# Display the input and resultant iamges
image1.show()
image2.show()
result.show()

輸入影像

color dots pillow logo

輸出

image blend

示例

這是一個演示使用 alpha 值為 1.0 的 PIL.Image.blend() 的示例。它將返回第二張影像的副本。

from PIL import Image

# Load two images
image1 = Image.open("Images/ColorDots.png")
image2 = Image.open("Images/pillow-logo-w.png")

# Blend the images with alpha = 2
result = Image.blend(image1, image2, alpha=1.0)

# Display the input and resultant iamges
image1.show()
image2.show()
result.show()

輸入影像

color dots pillow logo

輸出

pillow logo
廣告