Python Pillow - ImageChops.composite() 函式



ImageChops.composite() 函式用於透過使用透明蒙版混合兩個影像來建立合成影像。此函式是主 Image 模組中 composite 函式的別名。

語法

以下是該方法的語法:

PIL.ImageChops.composite(image1, image2, mask)

或者

PIL.Image.composite(image1, image2, mask)

引數

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

  • image1 - 要合成的第一個輸入影像。

  • image2 - 要合成的第二個輸入影像。它必須與第一個影像具有相同的模式和大小。

  • mask - 蒙版影像。此影像可以具有“1”、“L”或“RGBA”模式,並且必須與其他兩個影像具有相同的大小。

返回值

此函式的返回型別為 Image。

示例

示例 1

在此示例中,image1、image2 和 mask 是輸入影像,composite() 函式用於根據 mask 中的透明度資訊將它們混合在一起。

from PIL import Image, ImageChops

# Open the first image
image1 = Image.open('Images/Light.jpg')

# Open the second image with the same mode and size as the first image
image2 = Image.open('Images/TP-W.jpg')

# Open the mask image with mode "L" 
mask = Image.open("Images/mask.jpg").convert("L")

# Use the composite function from ImageChops to blend the images using the mask
composite_image = ImageChops.composite(image1, image2, mask)

# Display or save the resulting composite image
image1.show()
image2.show()
mask.show()
composite_image.show()

輸出

輸入影像 1

light

輸入影像 2

tp_w

輸入蒙版

mask

輸出合成影像

chops composite

示例 2

提供的示例建立一個畫素值為 128 的純灰色影像,並將其用作蒙版以將兩個影像混合在一起。

from PIL import Image, ImageChops

# Open the first image
image1 = Image.open('Images/TP-W.jpg')

# Open the second image with the same mode and size as the first image
image2 = Image.open('Images/rose.jpg').resize(image1.size)

# Create a solid gray mask image with a pixel value of 128
mask = Image.new("L", image1.size, 128)

# Use the composite function to blend the images using the mask
composite_image = Image.composite(image1, image2, mask)

# Display the input and resulting images
image1.show()
image2.show()
mask.show()
composite_image.show()

輸出

輸入影像 1

tp_w

輸入影像 2

red flower

輸入蒙版

mask image

輸出合成影像

imagechops composite

示例 3

此示例建立一個在黑色背景上帶有白色矩形的蒙版,並使用它將兩個影像混合在一起。

from PIL import Image, ImageDraw

# Open the first image
image1 = Image.open('Images/TP-W.jpg')

# Open the second image with the same mode and size as the first image
image2 = Image.open('Images/rose.jpg').resize(image1.size)

# Create a mask image with a white rectangle on a black background
mask = Image.new("L", image1.size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle((245, 45, 445, 345), fill=255)

# Use the composite function to blend the images using the mask
composite_image = Image.composite(image1, image2, mask)

# Display the input and resulting images
image1.show()
image2.show()
mask.show()
composite_image.show()

輸出

輸入影像 1

tp_w

輸入影像 2

red flower

輸入蒙版

bw box

輸出合成影像

output composite image
python_pillow_function_reference.htm
廣告