[파이썬] Pillow 이미지의 색상 교환하기

Pillow is a powerful image processing library in Python that allows you to perform various operations on images. One such operation is exchanging colors in an image. In this blog post, we will explore how to use Pillow to swap colors in an image.

Installation

Before we start, make sure you have Pillow installed. You can install it using pip:

pip install pillow

Usage

Step 1: Import the necessary libraries

To begin, import the required libraries - PIL (Pillow) and Image from PIL module.

from PIL import Image

Step 2: Load the image

Next, load the image on which you want to exchange colors using the open() function. Make sure the image is in the same directory as your Python script.

image = Image.open("image.jpg")

Step 3: Exchange the colors

Now, let’s say we want to swap the red color pixels with blue color pixels and vice versa. To do this, we can use the convert() method to change each pixel’s color to the desired color.

def swap_colors(pixel):
    # Get the RGB values of the pixel
    r, g, b = pixel

    # Swap the red and blue color values
    return (b, g, r)

# Apply the swap_colors() function to each pixel in the image
image = image.convert("RGB")
width, height = image.size
for x in range(width):
    for y in range(height):
        pixel = image.getpixel((x, y))
        swapped_pixel = swap_colors(pixel)
        image.putpixel((x, y), swapped_pixel)

Step 4: Save and display the modified image

Finally, you can save the modified image using the save() method and display it using the show() method.

image.save("modified_image.jpg")
image.show()

That’s it! You have successfully swapped the colors in your image using Pillow in Python.

Conclusion

Pillow provides a convenient way to manipulate colors in images using Python. By following the steps outlined in this blog post, you can easily swap colors in an image. Experiment with different color combinations to achieve unique visual effects.