Images often require adjustments in terms of brightness and contrast to enhance their visual appearance or facilitate further analysis. In this blog post, we will explore how to adjust the brightness and contrast of images using the imageio
library in Python.
Installing the imageio Library
Before we can get started, we need to make sure that the imageio
library is installed. If it’s not already installed, open your terminal or command prompt and run the following command:
pip install imageio
Importing the Required Libraries
To begin, let’s import the necessary libraries:
import imageio
import numpy as np
import matplotlib.pyplot as plt
Loading the Image
Next, we need to load the image on which we want to adjust the brightness and contrast. We can use the imread
function from imageio
to load the image as a NumPy array:
image_path = "path_to_your_image.jpg"
image = imageio.imread(image_path)
Adjusting the Brightness
To adjust the brightness, we can simply add or subtract a constant value from each pixel in the image array. We can use the NumPy library to perform this operation efficiently:
brightness_adjusted_image = image + 50
In the example above, we increased the brightness by adding 50 to each pixel value. Similarly, we can decrease the brightness by subtracting a constant value.
Adjusting the Contrast
To adjust the contrast, we can use a technique called histogram equalization. This technique redistributes the pixel values across the entire range of intensities, enhancing the overall contrast of the image. The imageio
library provides a convenient function imadjust
that performs histogram equalization:
contrast_adjusted_image = imageio.imadjust(image)
Displaying the Results
Finally, let’s display the original image, as well as the brightness and contrast-adjusted images, using the matplotlib
library:
plt.figure(figsize=(10, 4))
plt.subplot(131)
plt.imshow(image)
plt.title("Original Image")
plt.subplot(132)
plt.imshow(brightness_adjusted_image)
plt.title("Brightness Adjusted")
plt.subplot(133)
plt.imshow(contrast_adjusted_image)
plt.title("Contrast Adjusted")
plt.tight_layout()
plt.show()
In the code above, we create a figure with three subplots to show the original image, brightness adjusted image, and contrast adjusted image side by side.
Conclusion
In this blog post, we explored how to adjust the brightness and contrast of images using the imageio
library in Python. The ability to manipulate the brightness and contrast of images can greatly enhance their visual quality and aid in various image processing tasks. Experiment with different brightness and contrast values to achieve the desired results.