AI-powered Image Enhancer Python, AI
👤 Sharing: AI
```python
import cv2
import numpy as np
from PIL import Image, ImageEnhance
import os
def enhance_image(image_path, brightness=1.0, contrast=1.0, sharpness=1.0, color=1.0):
"""
Enhances an image using Pillow library.
Args:
image_path (str): Path to the image file.
brightness (float): Brightness factor (1.0 for original brightness).
contrast (float): Contrast factor (1.0 for original contrast).
sharpness (float): Sharpness factor (1.0 for original sharpness).
color (float): Color factor (1.0 for original color).
Returns:
PIL.Image.Image: Enhanced image object. Returns None if error occurs.
"""
try:
img = Image.open(image_path)
# Enhance Brightness
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(brightness)
# Enhance Contrast
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(contrast)
# Enhance Sharpness
enhancer = ImageEnhance.Sharpness(img)
img = enhancer.enhance(sharpness)
# Enhance Color
enhancer = ImageEnhance.Color(img)
img = enhancer.enhance(color)
return img
except FileNotFoundError:
print(f"Error: File not found at {image_path}")
return None
except Exception as e:
print(f"Error during image enhancement: {e}")
return None
def enhance_image_cv2(image_path, alpha=1.0, beta=0):
"""
Enhances an image using OpenCV. Primarily used for brightness and contrast.
Args:
image_path (str): Path to the image file.
alpha (float): Contrast control (1.0-3.0).
beta (int): Brightness control (0-100).
Returns:
numpy.ndarray: Enhanced image as a NumPy array. Returns None if error occurs.
"""
try:
img = cv2.imread(image_path)
if img is None:
print(f"Error: Could not read image at {image_path}")
return None
enhanced_img = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)
return enhanced_img
except FileNotFoundError:
print(f"Error: File not found at {image_path}")
return None
except Exception as e:
print(f"Error during image enhancement: {e}")
return None
def main():
"""
Demonstrates the usage of the image enhancement functions.
"""
# Example Usage (Pillow)
image_file = "input.jpg" # Replace with your image file name
output_file_pillow = "output_pillow.jpg"
# Create a dummy image if input.jpg does not exist
if not os.path.exists(image_file):
dummy_image = Image.new('RGB', (200, 200), color = 'red')
dummy_image.save(image_file)
enhanced_img_pillow = enhance_image(image_file, brightness=1.2, contrast=1.1, sharpness=1.3, color=1.0)
if enhanced_img_pillow:
enhanced_img_pillow.save(output_file_pillow)
print(f"Enhanced image saved to {output_file_pillow}")
# Example Usage (OpenCV)
output_file_cv2 = "output_cv2.jpg"
enhanced_img_cv2 = enhance_image_cv2(image_file, alpha=1.5, beta=20)
if enhanced_img_cv2 is not None:
cv2.imwrite(output_file_cv2, enhanced_img_cv2)
print(f"Enhanced image saved to {output_file_cv2}")
if __name__ == "__main__":
main()
```
👁️ Viewed: 9
Comments