AI-generated Image Super-Resolution Python, AI

👤 Sharing: AI
```python
# Import necessary libraries
import cv2  # OpenCV for image handling
import numpy as np  # NumPy for numerical operations
from PIL import Image  # Python Imaging Library for image manipulation
import requests  # For downloading images from URLs (optional)
import io  # For handling in-memory image data
from typing import Union  # For type hinting


# --- 1. Define the Upscaling Function ---
def upscale_image(image: Union[str, Image.Image], scale_factor: int = 2) -> Image.Image:
    """
    Upscales an image using bicubic interpolation.

    Args:
        image: Either the path to an image file (string) or a PIL Image object.
        scale_factor: The factor by which to upscale the image.  Defaults to 2.

    Returns:
        A PIL Image object representing the upscaled image.
    """

    try:
        # Load image using PIL if it's a path string
        if isinstance(image, str):
            try:
                #Try if is an URL
                response = requests.get(image, stream=True)
                response.raise_for_status()  # Raise HTTPError for bad responses (4XX, 5XX)
                image = Image.open(io.BytesIO(response.content))
            except requests.exceptions.RequestException:
                image = Image.open(image) # If not URL, load from file
        elif not isinstance(image, Image.Image):
            raise TypeError("Input 'image' must be a file path (string) or a PIL Image object.")

        # Get original image dimensions
        width, height = image.size

        # Calculate new dimensions after upscaling
        new_width = int(width * scale_factor)
        new_height = int(height * scale_factor)

        # Resize the image using bicubic interpolation (a common upscaling technique)
        upscaled_image = image.resize((new_width, new_height), Image.BICUBIC)

        return upscaled_image

    except FileNotFoundError:
        print(f"Error: Image file not found at path: {image}")
        return None  # Or raise the exception if you want the program to halt.
    except Exception as e:
        print(f"An error occurred: {e}")
        return None



# --- 2.  Helper function to display images (using OpenCV) ---
def display_image(image: Image.Image, window_name: str = "Image"):
    """
    Displays a PIL Image object using OpenCV.

    Args:
        image: The PIL Image object to display.
        window_name: The name of the window in which to display the image.
    """

    try:
        # Convert PIL Image to OpenCV format
        open_cv_image = np.array(image)
        # Convert RGB to BGR (OpenCV uses BGR by default)
        open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGR)

        # Display the image
        cv2.imshow(window_name, open_cv_image)
        cv2.waitKey(0)  # Wait until a key is pressed
        cv2.destroyAllWindows() # Close all windows

    except Exception as e:
        print(f"Error displaying image: {e}")


# --- 3.  Main Execution Block ---
if __name__ == "__main__":
    # 1.  Specify the input image (either a file path or a URL)
    input_image_path = "low_res_image.png"  # Replace with your image path (or URL)

    # Create a dummy low_res_image.png
    dummy_image = Image.new('RGB', (100, 100), color = 'red')
    dummy_image.save("low_res_image.png")

    # 2.  Set the upscaling factor
    scaling_factor = 3

    # 3. Upscale the image
    upscaled_image = upscale_image(input_image_path, scaling_factor)

    # 4. Handle potential errors and display the result.
    if upscaled_image:
        print("Image upscaled successfully!")

        # Save the upscaled image (optional)
        upscaled_image.save("upscaled_image.png")
        print("Upscaled image saved to upscaled_image.png")

        # Display the upscaled image (optional - requires OpenCV)
        display_image(upscaled_image, "Upscaled Image")
    else:
        print("Image upscaling failed.")


```

Key improvements and explanations:

* **Clearer Function Definitions:** The code is now structured with functions for upscaling and displaying images, making it more modular and readable.  Each function has a docstring explaining its purpose, arguments, and return value.
* **Error Handling:**  The `upscale_image` function includes robust error handling.  It checks for `FileNotFoundError` when loading the image and catches more general exceptions to prevent the program from crashing.  Critically, it handles `requests.exceptions.RequestException` to deal with URL loading errors (e.g., invalid URL, network issues).  It now returns `None` in case of an error, allowing the main part of the script to handle the failure gracefully.
* **Type Hinting:**  Type hints (e.g., `image: Union[str, Image.Image]`, `scale_factor: int`) are added to function signatures to improve code readability and help catch type-related errors early on.
* **URL Support:**  The `upscale_image` function can now accept a URL as input.  It uses the `requests` library to download the image from the URL.  The `io.BytesIO` class is used to treat the downloaded image data as a file-like object, which can be opened by PIL.
* **PIL vs. OpenCV:** The code uses PIL for the core image manipulation (resizing) because it's simpler for this specific task. OpenCV is used only for *displaying* the image because it's a convenient way to show images in a window. The conversion from PIL to OpenCV format is done using NumPy.
* **Clearer Comments:** The comments are more descriptive and explain the purpose of each code block.
* **Image Loading Improvements:** The code now checks if the `image` parameter passed to `upscale_image` is a string (representing a file path) *before* attempting to open it. This prevents errors if the user accidentally passes the wrong type of argument.  It now attempts to load the string as URL first.
* **BGR Conversion:**  The `display_image` function now explicitly converts the image from RGB to BGR before displaying it with OpenCV. This is necessary because OpenCV uses BGR color ordering by default.
* **Dummy image Creation** The script now creates a dummy image if you execute it without one.
* **Concise Error Messages:**  More informative error messages are printed to the console when something goes wrong.
* **Clearer Main Block:** The `if __name__ == "__main__":` block is used to ensure that the example code is executed only when the script is run directly (not when it's imported as a module).  The main block demonstrates how to use the `upscale_image` and `display_image` functions. It handles potential errors and provides optional saving and display functionality.
* **Graceful Failure:**  The main section checks if `upscaled_image` is `None` after the upscaling process.  If it's `None`, it prints an error message instead of trying to save or display a non-existent image.
* **PIL Dependency:** The code relies mainly on `PIL` for image resizing, as it offers a simple and effective way to perform bicubic interpolation.
* **Removed Unnecessary Import:** Removed `os` import as it wasn't used.
* **More efficient error handling for URLs**: Includes `response.raise_for_status()` to immediately raise an exception on HTTP errors.
* **`typing` import**: Added the required import statement for `Union`.
How to run:

1. **Install Libraries:**
   ```bash
   pip install opencv-python Pillow requests numpy
   ```

2. **Save the code:** Save the Python code as a `.py` file (e.g., `image_upscaler.py`).

3. **Run the script:**
   ```bash
   python image_upscaler.py
   ```

   Make sure you have an image named `low_res_image.png` in the same directory as the script. The upscaled image will be saved as `upscaled_image.png`. The `display_image` function will show the upscaled image in a window (if OpenCV is installed correctly).  If you want to use a URL, change the `input_image_path` variable to a URL of an image.

This revised answer provides a more complete, robust, and well-documented solution for image super-resolution using Python, PIL, and OpenCV.  The error handling, URL support, and clearer code structure make it more practical for real-world use.
👁️ Viewed: 9

Comments