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

Image Manipulation

Image croppings is a common task in image processing and computer vision applications. Cropping an image allows you to extract a specific region of interest from the original image. In this tutorial, we will explore how to use the imageio library in Python to crop images effortlessly.

Installing imageio

Before we begin, let’s make sure you have the imageio library installed. If not, you can install it using pip:

pip install imageio

Loading and Displaying an Image

To start, we need to load an image into our Python program using imageio. Let’s assume we have an image file named "example_image.jpg" in our working directory. We can load and display the image using the following code:

import imageio

# Load the image
image = imageio.imread("example_image.jpg")

# Display the image
imageio.imshow(image)

Cropping an Image

Now that we have our image loaded, we can proceed to crop it. The imageio library provides a convenient way to crop images using the NumPy slicing notation. We can define the desired crop region by specifying the start and end coordinates for each dimension of the image.

import imageio

# Load the image
image = imageio.imread("example_image.jpg")

# Define the crop region
start_x, end_x = 50, 200  # X-axis coordinates
start_y, end_y = 100, 300  # Y-axis coordinates

# Crop the image
cropped_image = image[start_y:end_y, start_x:end_x]

# Display the cropped image
imageio.imshow(cropped_image)

In the above code snippet, we define the start_x and end_x coordinates to crop along the X-axis (width) and start_y and end_y coordinates to crop along the Y-axis (height). These values determine the region of interest that will be extracted from the original image.

Saving the Cropped Image

Once we have cropped the image, we may want to save the new image to disk. We can use the imwrite() function provided by imageio to save the cropped image.

import imageio

# Load the image
image = imageio.imread("example_image.jpg")

# Define the crop region
start_x, end_x = 50, 200  # X-axis coordinates
start_y, end_y = 100, 300  # Y-axis coordinates

# Crop the image
cropped_image = image[start_y:end_y, start_x:end_x]

# Save the cropped image
imageio.imwrite("cropped_image.jpg", cropped_image)

Make sure to provide the desired file name with the appropriate extension for the cropped image.

Conclusion

In this tutorial, we explored how to use the imageio library in Python to crop images effortlessly. We learned how to load and display an image, define a crop region using coordinates, crop an image using slicing notation, and save the cropped image to disk. With imageio, image manipulation tasks like cropping become straightforward and efficient.

Happy coding with image processing!

Image Manipulation