[파이썬] imageio 이미지 스케일링

Image scaling is a common operation in image processing, where you adjust the size of an image while maintaining its aspect ratio. In Python, the imageio library provides an easy and efficient way to perform image scaling. In this article, we will explore how to use imageio to scale images in Python.

Installation

Before we get started, make sure you have imageio installed. If you don’t, you can install it using pip:

pip install imageio

Image Scaling with imageio

To scale an image in Python using imageio, follow these steps:

  1. Import the necessary libraries:
     import imageio
     import numpy as np
    
  2. Load the image using imageio.imread(). This will read the image into a NumPy array:
     img = imageio.imread('input.jpg')
    
  3. Calculate the desired scale factor. For example, if you want to scale the image by a factor of 0.5, you would set scale_factor = 0.5.

  4. Use the imageio.imresize() function to scale the image. This function takes the image and the scale factor as input and returns the scaled image as a NumPy array:
     scaled_img = imageio.imresize(img, scale_factor)
    
  5. Save the scaled image using imageio.imwrite(). Specify the output file name and the scaled image array:
     imageio.imwrite('output.jpg', scaled_img)
    
  6. Optionally, display the scaled image using a plotting library like Matplotlib:
     import matplotlib.pyplot as plt
    
     plt.imshow(scaled_img)
     plt.axis('off')
     plt.show()
    

And that’s it! You have successfully scaled an image using imageio in Python.

Example

Here’s a complete example that scales an image by a factor of 0.5:

import imageio
import numpy as np
import matplotlib.pyplot as plt

# Load the image
img = imageio.imread('input.jpg')

# Scale factor
scale_factor = 0.5

# Scale the image
scaled_img = imageio.imresize(img, scale_factor)

# Save the scaled image
imageio.imwrite('output.jpg', scaled_img)

# Display the scaled image
plt.imshow(scaled_img)
plt.axis('off')
plt.show()

Conclusion

Image scaling is an essential task in various domains, such as computer vision and digital media. With imageio library in Python, you can easily scale images while preserving their aspect ratio. This article provided a simple guide on using imageio for image scaling in Python. Give it a try and see how you can incorporate it into your own image processing projects!