Contrast Enhancement Techniques in Image Processing using Python
In this tutorial, we will walk through two essential tasks in image processing. The first task demonstrates how to perform contrast enhancement without using OpenCV, and the second compares different smoothing methods using OpenCV. Both sections include detailed code explanations and visual results using Python libraries.
Contrast Enhancement without OpenCV
This task covers loading an image, converting it to grayscale manually, and then applying contrast enhancement through histogram stretching.
Step 1: Import Required Libraries
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
Step 2: Load and Display the Original Image
# Load the image using PIL
img_pil = Image.open('/content/img2.jpg')
plt.figure(figsize=(6, 6))
plt.imshow(img_pil)
plt.title('Original Image (Task 1)')
plt.axis('off')
plt.show()
Step 3: Convert to Grayscale Manually
The following code converts the loaded image to grayscale using the formula:
# Convert image to a numpy array
img_array = np.array(img_pil)
# If the image has an alpha channel, remove it
if img_array.shape[2] == 4:
img_array = img_array[:, :, :3]
# Apply the grayscale formula
gray_manual = np.dot(img_array[..., :3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
# Display the grayscale image
plt.figure(figsize=(6, 6))
plt.imshow(gray_manual, cmap='gray')
plt.title('Manual Grayscale (Task 1)')
plt.axis('off')
plt.show()
Step 4: Contrast Enhancement Using Histogram Stretching
def contrast_stretch(image):
min_val = np.min(image)
max_val = np.max(image)
if max_val == min_val:
return image # Avoid division by zero
stretched = (image - min_val) * (255.0 / (max_val - min_val))
return stretched.astype(np.uint8)
enhanced_image = contrast_stretch(gray_manual)
# Display the original grayscale and contrast-enhanced images side by side
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(gray_manual, cmap='gray')
plt.title('Original Grayscale')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(enhanced_image, cmap='gray')
plt.title('Contrast Enhanced')
plt.axis('off')
plt.tight_layout()
plt.show()
Compare Smoothing Methods using OpenCV
This task demonstrates how to load an image with OpenCV and then apply various smoothing filters to reduce noise and blur, comparing the effects of each method.
Step 1: Import Libraries and Load the Image
import cv2
# Load the image using OpenCV
img_cv = cv2.imread('/content/img.png')
# Convert from BGR to RGB for display with matplotlib
img_cv_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
Step 2: Apply Different Smoothing Techniques
The code below applies four different smoothing methods: Averaging Filter, Gaussian Blur, Median Blur, and Bilateral Filter. The kernel sizes and parameters are set to achieve stronger blurring for comparison.
# Averaging Filter
avg_blur = cv2.blur(img_cv, (15, 15))
avg_blur_rgb = cv2.cvtColor(avg_blur, cv2.COLOR_BGR2RGB)
# Gaussian Blur
gauss_blur = cv2.GaussianBlur(img_cv, (15, 15), 5)
gauss_blur_rgb = cv2.cvtColor(gauss_blur, cv2.COLOR_BGR2RGB)
# Median Blur
median_blur = cv2.medianBlur(img_cv, 15)
median_blur_rgb = cv2.cvtColor(median_blur, cv2.COLOR_BGR2RGB)
# Bilateral Filter
bilateral_blur = cv2.bilateralFilter(img_cv, 15, 150, 150)
bilateral_blur_rgb = cv2.cvtColor(bilateral_blur, cv2.COLOR_BGR2RGB)
Step 3: Display the Results
plt.figure(figsize=(20, 10))
plt.subplot(2, 3, 1)
plt.imshow(img_cv_rgb)
plt.title('Original Image (Task 2)')
plt.axis('off')
plt.subplot(2, 3, 2)
plt.imshow(avg_blur_rgb)
plt.title('Averaging Filter')
plt.axis('off')
plt.subplot(2, 3, 3)
plt.imshow(gauss_blur_rgb)
plt.title('Gaussian Blur')
plt.axis('off')
plt.subplot(2, 3, 4)
plt.imshow(median_blur_rgb)
plt.title('Median Blur')
plt.axis('off')
plt.subplot(2, 3, 5)
plt.imshow(bilateral_blur_rgb)
plt.title('Bilateral Filter')
plt.axis('off')
plt.tight_layout()
plt.show()
Step 4: Explanation of the Smoothing Methods
Each smoothing filter has its own strengths and weaknesses:
- Averaging Filter: Applies a simple uniform blur, reducing noise but also blurring edges.
- Gaussian Blur: Uses a Gaussian kernel for weighted averaging, providing better noise reduction with less edge blurring compared to the averaging filter.
- Median Blur: Effective against salt-and-pepper noise while preserving edges better than linear filters.
- Bilateral Filter: Maintains edges by considering both spatial and intensity differences, although it is more computationally expensive.
You can also print a summary of these methods:
print("Comparison of Smoothing Methods:")
print("- Averaging Filter: Simple uniform smoothing. Reduces noise but blurs edges significantly.")
print("- Gaussian Blur: Uses Gaussian kernel for weighted averaging. Better noise reduction with less edge blurring compared to averaging.")
print("- Median Blur: Effective against salt-and-pepper noise. Preserves edges better than linear filters.")
print("- Bilateral Filter: Maintains edges by considering both spatial and intensity differences. More computationally expensive but preserves edges effectively.")
Conclusion
This tutorial showcased two important image processing techniques. You learned how to enhance contrast by stretching the histogram of a manually converted grayscale image and compared several smoothing methods using OpenCV. Experiment with the parameters and filters to better understand their effects on different images.
Comments
Post a Comment