write the python code Enhance the image to reduce the overexposure caused by streetlights and white light bulbs, making the scene clearer and all the features, such as objects, structures, and terrain, visible with greater detail. Apply appropriate image-processing algorithms to address the light glare and provide an explanation of each algorithm used, detailing their benefits and limitations. apply all various algorithms include if statements to between the algorithms in the pipeline. explain the algorithms it benefits and drawbacks and it important paramters.
Assistant
Certainly! Enhancing an image with overexposure caused by streetlights and white light bulbs involves several image processing techniques. Below is a Python script that implements a pipeline to address this issue. The pipeline includes various algorithms, each with its own benefits and limitations. The script uses conditional statements (if statements) to apply different algorithms based on specific conditions or user preferences.
Prerequisites:
Before running the script, ensure you have the following Python libraries installed:
opencv-python for image processing
numpy for numerical operations
matplotlib for displaying images
You can install them using pip:
bash
pip install opencv-python numpy matplotlib
Python Script:
python
import cv2
import numpy as np
import matplotlib.pyplot as plt
def load_image(path):
"""Load an image from the specified file path."""
image = cv2.imread(path)
if image is None:
raise ValueError("Image not found or the path is incorrect")
# Convert BGR (OpenCV default) to RGB for display purposes
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image
def detect_overexposed_regions(image, threshold=240):
"""
Detect overexposed regions in the image.
Pixels above the threshold are considered overexposed.
"""
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
_, mask = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
return mask
def inpaint_overexposed(image, mask):
"""
Inpaint the overexposed regions detected by the mask.
Uses the Telea inpainting algorithm.
"""
# Convert RGB back to BGR for OpenCV inpainting
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
inpainted = cv2.inpaint(image_bgr, mask, 3, cv2.INPAINT_TELEA)
# Convert back to RGB
inpainted = cv2.cvtColor(inpainted, cv2.COLOR_BGR2RGB)
return inpainted
def histogram_equalization(image):
"""
Apply histogram equalization to enhance the contrast of the image.
Only applied to the luminance channel in YUV color space.
"""
img_yuv = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
# Equalize the histogram of the Y (luminance) channel
img_yuv[:, :, 0] = cv2.equalizeHist(img_yuv[:, :, 0])
# Convert back to RGB
equalized = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2RGB)
return equalized
def adaptive_histogram_equalization(image, clip_limit=2.0, tile_grid_size=(8,8)):
"""
Apply CLAHE (Contrast Limited Adaptive Histogram Equalization) to enhance local contrast.
"""
img_yuv = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size)
img_yuv[:, :, 0] = clahe.apply(img_yuv[:, :, 0])
# Convert back to RGB
clahe_img = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2RGB)
return clahe_img
def gamma_correction(image, gamma=1.0):
"""
Apply gamma correction to adjust the brightness of the image.
"""
inv_gamma = 1.0 / gamma
# Build a lookup table mapping pixel values [0, 255] to their adjusted gamma values
table = np.array([((i / 255.0) ** inv_gamma) * 255
for i in np.arange(256)]).astype("uint8")
# Apply gamma correction using the lookup table
return cv2.LUT(image, table)
def reduce_glare(image):
"""
Apply a blur to reduce glare in the image.
"""
# Use a Gaussian blur to smooth out bright regions
blurred = cv2.GaussianBlur(image, (15, 15), 0)
# Blend the blurred image with the original image
reduced_glare = cv2.addWeighted(image, 0.7, blurred, 0.3, 0)
return reduced_glare
def enhance_image(image_path, apply_inpainting=True, apply_hist_eq=True,
apply_adapt_hist_eq=False, apply_gamma_corr=False,
apply_glare_reduction=False, gamma_value=1.0):
"""
Enhance the image by applying various image processing algorithms.
Parameters can be toggled to apply or skip specific algorithms.
"""
# Load image
image = load_image(image_path)
enhanced_image = image.copy()
# Step 1: Detect overexposed regions and inpaint
if apply_inpainting:
mask = detect_overexposed_regions(enhanced_image)
# If significant overexposed areas are detected, apply inpainting
if np.sum(mask) > 0:
enhanced_image = inpaint_overexposed(enhanced_image, mask)
print("Applied Inpainting to reduce overexposure.")
else:
print("No significant overexposed regions detected. Skipping Inpainting.")
# Step 2: Histogram Equalization
if apply_hist_eq:
enhanced_image = histogram_equalization(enhanced_image)
print("Applied Histogram Equalization to enhance contrast.")
# Step 3: Adaptive Histogram Equalization (CLAHE)
if apply_adapt_hist_eq:
enhanced_image = adaptive_histogram_equalization(enhanced_image)
print("Applied Adaptive Histogram Equalization (CLAHE) for local contrast enhancement.")
# Step 4: Gamma Correction
if apply_gamma_corr:
enhanced_image = gamma_correction(enhanced_image, gamma=gamma_value)
print(f"Applied Gamma Correction with gamma = {gamma_value}.")
# Step 5: Glare Reduction
if apply_glare_reduction:
enhanced_image = reduce_glare(enhanced_image)
print("Applied Glare Reduction using Gaussian Blurring and blending.")
return enhanced_image
def display_images(original, enhanced):
"""Display the original and enhanced images side by side."""
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(original)
plt.title("Original Image")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(enhanced)
plt.title("Enhanced Image")
plt.axis('off')
plt.show()
if __name__ == "__main__":
# Path to the input image
image_path = 'input_image.jpg' # Replace with your image path
# Enhance the image with desired parameters
enhanced = enhance_image(
image_path,
apply_inpainting=True,
apply_hist_eq=True,
apply_adapt_hist_eq=True,
apply_gamma_corr=True,
apply_glare_reduction=True,
gamma_value=1.2 # Adjust gamma as needed
)
# Load the original image for comparison
original = load_image(image_path)
# Display the original and enhanced images
display_images(original, enhanced)
# Save the enhanced image
enhanced_bgr = cv2.cvtColor(enhanced, cv2.COLOR_RGB2BGR)
cv2.imwrite('enhanced_image.jpg', enhanced_bgr)
print("Enhanced image saved as 'enhanced_image.jpg'.")
Explanation of Each Algorithm:
Overexposed Region Detection and Inpainting:
Algorithm: Detects pixels with brightness above a certain threshold (e.g., 240 out of 255) and uses the Telea inpainting algorithm to fill in these regions.
Benefits:
Removes bright glare spots, restoring details in overexposed areas.
Telea's method is fast and generally produces visually pleasing results.
Drawbacks:
May not perfectly restore complex textures.
If large areas are overexposed, inpainting might not recover all details.
Important Parameters:
threshold: Determines what is considered overexposed.
Inpainting radius: Affects the extent of inpainting around detected regions.
Histogram Equalization:
Algorithm: Enhances the global contrast of the image by spreading out the most frequent intensity values.
Benefits:
Improves contrast in images with poor dynamic range.
Simple and fast to compute.
Drawbacks:
Can lead to over-enhancement, making the image look unnatural.
Not effective for enhancing local contrast.
Important Parameters:
None in basic histogram equalization, but applied to specific channels (e.g., luminance).
Adaptive Histogram Equalization (CLAHE):
Algorithm: Enhances local contrast by applying histogram equalization to small regions (tiles) of the image.
Benefits:
Improves local contrast without affecting the global contrast.
Prevents over-amplification of noise due to the clipping limit.
Drawbacks:
Computationally more intensive than global histogram equalization.
Parameters like clip limit and tile grid size need careful tuning.
Important Parameters:
clipLimit: Prevents over-amplification by limiting the contrast enhancement.
tileGridSize: Defines the size of the region for local equalization.
How the Pipeline Works:
Loading the Image:
The image is loaded and converted from BGR to RGB color space for accurate color representation.
Overexposed Region Detection and Inpainting:
Overexposed regions are detected based on a brightness threshold.
Inpainting is applied to these regions to restore details.
Histogram Equalization:
Global contrast is enhanced to make features more distinguishable.
Adaptive Histogram Equalization (CLAHE):
Local contrast is further enhanced to bring out details in specific areas without affecting the entire image.
Gamma Correction:
Adjusts the overall brightness of the image to achieve the desired visual effect.
Glare Reduction:
Gaussian blurring and blending are used to reduce glare from bright light sources, making the scene clearer.
Usage Instructions:
Prepare the Image:
Ensure you have an input image (e.g., input_image.jpg) placed in the same directory as the script or provide the correct path.
Run the Script:
Execute the script using Python:
bash
python enhance_image.py
Adjust Parameters (Optional):
You can toggle the application of specific algorithms by setting the corresponding parameters in the enhance_image function call.
Adjust gamma_value to control the degree of gamma correction.
View and Save the Enhanced Image:
The script will display the original and enhanced images side by side.
The enhanced image is saved as enhanced_image.jpg in the same directory.
Conclusion:
The provided Python script offers a comprehensive pipeline to enhance images affected by overexposure due to streetlights and white light bulbs. By combining multiple image processing techniques, it effectively reduces glare, restores details in bright regions, and enhances both global and local contrast. Adjusting the parameters allows for customization based on specific image characteristics and desired outcomes.