AI-enhanced Photo Retouching Python, AI

👤 Sharing: AI
```python
import cv2
import numpy as np
from PIL import Image, ImageFilter
import rembg  # Requires installation: pip install rembg
import warnings

warnings.filterwarnings("ignore")  # Suppress some warnings for cleaner output.  Remove if you want to see warnings.


def enhance_photo(image_path, remove_background=False, sharpen=False, denoise=False, color_correct=False, face_enhance=False):
    """
    Enhances a photo using various AI-powered and traditional image processing techniques.

    Args:
        image_path (str): Path to the input image.
        remove_background (bool): Whether to remove the background (using rembg).  Requires internet connection.
        sharpen (bool): Whether to apply sharpening.
        denoise (bool): Whether to apply denoising.
        color_correct (bool): Whether to apply basic color correction.
        face_enhance (bool): Whether to attempt face enhancement (placeholder - requires advanced models and libraries).

    Returns:
        PIL.Image.Image: The enhanced image as a PIL Image object.  Returns None on error.
    """

    try:
        img = Image.open(image_path)
    except FileNotFoundError:
        print(f"Error: Image not found at {image_path}")
        return None
    except Exception as e:
        print(f"Error: Could not open image.  {e}")
        return None

    # 1. Remove Background (rembg)
    if remove_background:
        try:
            #rembg requires pillow for image handling
            output = rembg.remove(img)  # Remove background
            img = output  # Update img with the background-removed image
        except Exception as e:
            print(f"Error removing background: {e}")
            # Continue without background removal if fails - CRITICAL to not have fatal error here.

    # 2. Sharpen
    if sharpen:
        try:
            img = img.filter(ImageFilter.SHARPEN)
        except Exception as e:
            print(f"Error sharpening: {e}")


    # 3. Denoise (using OpenCV)
    if denoise:
        try:
            # Convert PIL Image to NumPy array (OpenCV format)
            img_np = np.array(img)
            img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR) # Convert to BGR for OpenCV

            # Apply non-local means denoising (adjust parameters as needed)
            img_np = cv2.fastNlMeansDenoisingColored(img_np, None, 10, 10, 7, 21)

            # Convert back to PIL Image
            img = Image.fromarray(cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)) #Convert back to RGB
        except Exception as e:
            print(f"Error denoising: {e}")

    # 4. Color Correction
    if color_correct:
        try:
            # Simple color correction (adjust brightness and contrast)
            img = img.convert("RGB")
            img = ImageEnhance.Brightness(img).enhance(1.1) # Increase brightness
            img = ImageEnhance.Contrast(img).enhance(1.2)   # Increase contrast
            img = ImageEnhance.Color(img).enhance(1.1)      # Enhance color saturation

        except Exception as e:
            print(f"Error color correcting: {e}")


    # 5. Face Enhancement (Placeholder - requires advanced models)
    if face_enhance:
        print("Face enhancement is a placeholder.  Requires advanced models and libraries (e.g., GFPGAN, CodeFormer).")
        # This section would ideally contain code to detect faces, crop them,
        # enhance the faces using a specialized model, and then paste them back
        # into the original image.  This is a *significantly* more complex task.

    return img


if __name__ == '__main__':
    from PIL import ImageEnhance #moved import here to avoid global scope

    # Example Usage:  Adjust the parameters as needed.  Be mindful of file paths.
    input_image_path = "input.jpg"  # Replace with your image path
    output_image_path = "output_enhanced.jpg"

    #Create a dummy image if input.jpg doesn't exist so the example can run.
    try:
        img = Image.open(input_image_path)
    except FileNotFoundError:
        print("Creating a dummy image 'input.jpg' for demonstration purposes.")
        img = Image.new('RGB', (512, 512), color = 'red')
        img.save(input_image_path)



    enhanced_image = enhance_photo(input_image_path,
                                     remove_background=True,  # Try removing the background
                                     sharpen=True,
                                     denoise=True,
                                     color_correct=True,
                                     face_enhance=False) #Face enhancement is a placeholder and requires additional libraries

    if enhanced_image:
        try:
            enhanced_image.save(output_image_path)
            print(f"Enhanced image saved to {output_image_path}")
        except Exception as e:
            print(f"Error saving enhanced image: {e}")
    else:
        print("Image enhancement failed.")
```
👁️ Viewed: 19

Comments