[파이썬] imageio 이미지 투명도 설정

In this blog post, we will explore how to use the imageio library in Python to set the transparency of an image. Transparency, also known as alpha channel, allows us to make parts of an image transparent, revealing the underlying content or background.

Installing Imageio

Before we can start, let’s make sure we have imageio installed. You can install it using pip:

pip install imageio

Loading an Image

Let’s start by loading an image using imageio:

import imageio

# Load the image
image = imageio.imread("path/to/image.png")

Make sure to replace "path/to/image.png" with the actual path to your image file.

Checking Image Transparency

Before we can set the transparency of an image, let’s check if the image already has an alpha channel. We can do this by examining the shape attribute of the loaded image. If the shape has four dimensions, it means the image already has transparency.

if image.shape[2] == 4:
    print("Image has transparency.")
else:
    print("Image does not have transparency.")

Setting Image Transparency

If the image does not have an alpha channel, we can manually add it by creating a new image with four channels (red, green, blue, and alpha). We can then copy the RGB channels from the original image and set the alpha value as per our requirement.

import numpy as np

# Create a new image with transparency
transparent_image = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)

# Copy RGB channels from the original image
transparent_image[:, :, :3] = image[:, :, :3]

# Set alpha channel to 0.5 (50% transparency)
transparent_image[:, :, 3] = int(0.5 * 255)

# Save the image with transparency
imageio.imwrite("path/to/transparent_image.png", transparent_image)

Make sure to replace "path/to/transparent_image.png" with the desired path and filename for the transparent image.

Conclusion

In this blog post, we learned how to use imageio to set the transparency of an image in Python. We checked if the image already has transparency and, if not, manually added an alpha channel to the image. By setting the alpha values, we can control the transparency level of specific regions in the image.

Using imageio, we can easily incorporate transparency functionality into our image processing scripts or applications.

Keep exploring and experimenting with imageio to discover other powerful image manipulation techniques!