跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI

combine two images with equal size

编辑日期: 2027-07-07 文章阅读:

Code

from PIL import Image

# Load the images
image1 = Image.open("img1.png")
image2 = Image.open("img2.png")

# Resize both images to 32x32 pixels
image1 = image1.resize((32, 32))
image2 = image2.resize((32, 32))

# Convert images to RGBA if they are not already
image1 = image1.convert("RGBA")
image2 = image2.convert("RGBA")

# Blend images with equal alpha values
blended_image = Image.blend(image1, image2, alpha=0.5)

# Save the result
blended_image.save("merged_image_32x32.png")

# Optionally display the result
blended_image.show()

Explain

here's a line-by-line explanation of the given code in English:

from PIL import Image

This line imports the Image class from the Python Imaging Library (PIL), which is used to handle image processing tasks.

# Load the images
image1 = Image.open("img1.png")
image2 = Image.open("img2.png")

These lines load two images from the files img1.png and img2.png, respectively, into image1 and image2 variables.

# Resize both images to 32x32 pixels
image1 = image1.resize((32, 32))
image2 = image2.resize((32, 32))

These lines resize both images to 32x32 pixels.

# Convert images to RGBA if they are not already
image1 = image1.convert("RGBA")
image2 = image2.convert("RGBA")

These lines convert both images to the RGBA mode, which includes the Red, Green, Blue, and Alpha (transparency) channels, if they are not already in that mode.

# Blend images with equal alpha values
blended_image = Image.blend(image1, image2, alpha=0.5)

This line blends the two images together with equal alpha values. The alpha parameter of 0.5 means each image contributes equally to the final blended image.

# Save the result
blended_image.save("merged_image_32x32.png")

This line saves the blended image to a new file named merged_image_32x32.png.

# Optionally display the result
blended_image.show()

This line optionally displays the blended image using the default image viewer on your system.

大家在看

京ICP备20031037号-1 | AI之家 | AI资讯 | Python200 | 数据分析