[파이썬] Pillow 색상 관리

Pillow is a powerful Python library that allows us to perform various image processing tasks. One of the important aspects of image processing is managing colors in images. In this blog post, we will explore how to use Pillow to manipulate colors in images.

Installing Pillow

Before we get started, let’s make sure we have Pillow installed. If not, you can install it using pip:

pip install pillow

Loading and Displaying an Image

To work with an image, we first need to load it using Pillow. Let’s assume we have an image file called “image.jpg” in the same directory. We can load and display it using the following code:

from PIL import Image

# Open the image file
image = Image.open("image.jpg")

# Display the image
image.show()

Converting Image to Grayscale

If we want to convert our image to grayscale, we can use the convert() method of the Image class. Here’s an example:

from PIL import Image

# Open the image file
image = Image.open("image.jpg")

# Convert the image to grayscale
grayscale_image = image.convert("L")

# Display the grayscale image
grayscale_image.show()

Modifying Image Colors

Pillow provides various methods to modify the colors in an image. Some common operations include:

Adjusting Brightness

We can control the brightness of an image using the ImageEnhance module. Here’s an example of increasing the brightness of an image by a factor of 1.5:

from PIL import ImageEnhance

# Open the image file
image = Image.open("image.jpg")

# Enhance the brightness
enhancer = ImageEnhance.Brightness(image)
bright_image = enhancer.enhance(1.5)

# Display the modified image
bright_image.show()

Adjusting Contrast

To adjust the contrast of an image, we can use the ImageEnhance module. Here’s an example of increasing the contrast of an image by a factor of 2:

from PIL import ImageEnhance

# Open the image file
image = Image.open("image.jpg")

# Enhance the contrast
enhancer = ImageEnhance.Contrast(image)
contrast_image = enhancer.enhance(2)

# Display the modified image
contrast_image.show()

Applying Filters

Pillow provides a variety of filters that can be applied to an image. Here’s an example of applying the “Sepia” filter to an image:

```python from PIL import ImageFilter

Open the image file

image = Image.open(“image.jpg”)

Apply the Sepia filter

sepia_image = image.filter(ImageFilter.SEP