[파이썬] Pillow 모자이크 처리하기

Image manipulation is a common task in computer vision and image processing applications. One common technique used is the pixelization or mosaic effect. In this blog post, we will explore how to achieve this effect using the Pillow library in Python.

Installing Pillow

Before we begin, let’s make sure Pillow is installed. You can install Pillow using pip with the following command:

pip install pillow

Loading and Displaying the Image

To start, we need to load an image and display it to verify that Pillow is working correctly. Let’s use the following code to load and display an image using Pillow:

from PIL import Image

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

# Display the image
img.show()

Make sure to replace “image.jpg” with the path to your own image file.

Applying the Mosaic Effect

Now that we have our image loaded, let’s move on to applying the mosaic effect. In this effect, we divide the image into small regions and replace each region with the average color of that region. Let’s use the following code to achieve this:

from PIL import Image

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

# Define the size of mosaic regions
region_size = 10

# Get the width and height of the image
width, height = img.size

# Loop through each region
for y in range(0, height, region_size):
    for x in range(0, width, region_size):
        # Get the average color of the region
        region = img.crop((x, y, x+region_size, y+region_size))
        average_color = region.resize((1, 1)).getpixel((0, 0))

        # Replace the region with the average color
        img.paste(average_color, (x, y, x+region_size, y+region_size))

# Display the mosaic image
img.show()

In the above code, we divide the image into small regions based on the specified region_size. Then, we calculate the average color of each region by cropping the image and resizing the cropped region to a single pixel. Finally, we paste the average color back onto the image at the corresponding region.

Conclusion

In this blog post, we learned how to create a mosaic effect using the Pillow library in Python. This effect can be used to add a creative and artistic touch to your images. Pillow provides a wide range of functionalities for image manipulation, and the mosaic effect is just one example. You can explore Pillow’s documentation to discover more ways to enhance your image processing workflows.

Feel free to experiment with different region sizes or apply the effect on different types of images to achieve unique visual effects. Happy coding!