Python Pillow - 影像合成



什麼是影像合成?

在 Pillow 中,影像合成涉及將兩張或多張影像組合起來以建立新的影像。此過程通常包括根據某些標準(例如透明度或特定混合模式)將一張影像的畫素值與另一張影像的畫素值混合。

Pillow 提供了 `Image.alpha_composite()` 方法用於影像合成,尤其是在處理 Alpha(透明度)通道時。它通常用於將一張影像疊加到另一張影像上,新增水印或建立特殊效果。

以下是與 Pillow 中的影像合成相關的關鍵概念:

影像合成

  • 透過將一張影像疊加到另一張影像上來組合影像以建立新的影像。

  • 影像合成通常用於新增水印或建立特殊效果。

Alpha 通道

  • Alpha 通道表示影像中每個畫素的透明度。

  • 具有 Alpha 通道的影像可以更無縫地合成,從而實現平滑混合。

`Image.alpha_composite()` 方法

Pillow 中的 `Image.alpha_composite()` 方法用於使用它們的 Alpha 通道合成兩張影像。它接受兩個 `Image` 物件作為輸入,並返回一個包含合成結果的新 `Image`。

以下是 `Image.alpha_composite()` 方法的語法和引數:

PIL.Image.alpha_composite(image1, image2)

其中:

  • `image1` - 將第二張影像合成到的背景影像。

  • `image2` - 將合成到背景影像上的前景影像。

示例

此示例演示如何使用 `Image.alpha_composite()` 方法合成兩張影像。

from PIL import Image

#Open or create the background image
background = Image.open("Images/decore.png")

#Open or create the foreground image with transparency
foreground = Image.open("Images/library_banner.png")

#Ensure that both images have the same size
if background.size != foreground.size:
    foreground = foreground.resize(background.size)

#Perform alpha compositing
result = Image.alpha_composite(background, foreground)

# Display the resulting image
result.show()

待使用的影像

decore library_banner

輸出

composite

使用影像合成新增水印

為影像新增水印是影像合成任務中的一個應用。您可以將水印疊加到影像上的特定位置和透明度。這是透過為水印建立一個新圖層並使用 `Image.alpha_composite()` 方法將其與底層影像混合來實現的。

示例

此示例演示如何使用 `Image.alpha_composite()` 方法將水印新增到影像中。水印影像以可調節的透明度放置在底層影像的頂部。

from PIL import Image

# Load the images and convert them to RGBA
image = Image.open('Images/yellow_car.jpg').convert('RGBA')
watermark = Image.open('Images/reading_img2.png').convert('RGBA')

# Create an empty RGBA layer with the same size as the image
layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
layer.paste(watermark, (20, 20))

# Create a copy of the layer and adjust the alpha transparency
layer2 = layer.copy()
layer2.putalpha(128)

# Merge the layer with its transparent copy using the alpha mask
layer.paste(layer2, (0, 0), layer2)

# Composite the original image with the watermark layer
result = Image.alpha_composite(image, layer)

# Display the resulting image
result.show()

待使用的影像

yellow_car.jpg

水印影像

reading_img2

輸出

composite_2
廣告