[파이썬] Pillow 이미지 자르기

Images play an important role in various applications, and sometimes we may need to crop or cut out specific portions of an image to focus on certain details or resize it for a specific purpose. In this blog post, we will explore how to use the Pillow library in Python to crop images.

Installing Pillow

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

pip install pillow

Cropping an Image

To crop an image using Pillow, we need to follow these steps:

  1. Open the image using the Image.open() method.
  2. Define the box coordinates for the region you want to crop.
  3. Use the Image.crop() method to crop the image.
  4. Save the cropped image using the Image.save() method.

Here’s an example code snippet that demonstrates how to crop an image using Pillow:

from PIL import Image

# Open the image
image = Image.open('path_to_your_image.jpg')

# Define the region to crop using left, upper, right, and lower coordinates
box = (100, 100, 400, 400)

# Crop the image
cropped_image = image.crop(box)

# Save the cropped image
cropped_image.save('path_to_save_cropped_image.jpg')

Make sure to replace 'path_to_your_image.jpg' with the actual path to your image file. Similarly, replace 'path_to_save_cropped_image.jpg' with the desired path to save the cropped image.

In the example above, we set the box coordinates to (100, 100, 400, 400), which means we want to crop a region starting from the pixel at coordinates (100, 100) to (400, 400).

Conclusion

Cropping images is a useful technique to extract specific parts or resize images for different purposes. With the help of the Pillow library in Python, we can easily achieve this. I hope this blog post has provided you with a good starting point for cropping images using Pillow. Feel free to explore other functionalities of Pillow to further enhance your image processing capabilities.