Batch Upscaling Low-Resolution Images with Stability AI API
Automating an annoyingly repeatitive task using ChatGPT as a sidekick

Batch Upscaling Low-Resolution Images with Stability AI API

As content creators, we often run into the problem of low-resolution images. Recently, I was working on an e-learning project where the client provided about 30 small, low-resolution images embedded in a document. Manually upscaling each image would take ages, so I turned to AI to automate the process.

The Problem

I was handed 30+ low-res images that needed to be upscaled to a higher quality. Normally, this would involve uploading each image one by one to an online upscaling service. That’s fine for a few images, but not ideal for batch processing.

The Solution: Automating with ChatGPT and Stability AI

Rather than doing this manually, I decided to use ChatGPT and Stability AI to automate the entire process. In a few steps, I was able to create a Python script that upscaled all the images directly on my desktop.

Step-by-Step Process:

  1. Describing the Problem to ChatGPT: I started by explaining the problem to ChatGPT and asked it to help me write a Python script using Stability AI’s image upscaling model.

I have 30 low-resolution images, and I need to upscale them in bulk. Can you help me create a Python script using Stability AI to automate this?

  1. ChatGPT responded by suggesting I use the stability-sdk library, which makes interacting with the Stability AI API straightforward.
  2. Integrating Stability AI: To get started, I needed to install the stability-sdk using pip:

pip3 install stability-sdk        

Then, I shared the Stability AI documentation with ChatGPT, and it guided me through writing the script.

  1. Refining the Script: After a bit of back-and-forth, I ended up with a Python script that:

  • Reads all images from a folder.
  • Resizes any that are too large for the Stability AI API.
  • Uses Stability AI’s upscaling model to improve their quality.
  • Saves the results in a new folder.

Here’s the final Python script:

import os
from stability_sdk import client
import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
from PIL import Image
from io import BytesIO

# Set your Stability AI API key
API_KEY = "your_actual_api_key"  # Replace this with your Stability API key

# Initialize Stability AI client with your API key
stability_api = client.StabilityInference(
    key=API_KEY,  # Using the API key directly here
    verbose=True,
)

# Function to resize images that are too large for the Stability API
def resize_image_if_needed(img, max_pixels=1048576):
    width, height = img.size
    total_pixels = width * height

    if total_pixels > max_pixels:
        aspect_ratio = width / height
        new_width = int((max_pixels * aspect_ratio) ** 0.5)
        new_height = int(new_width / aspect_ratio)
        print(f"Resizing image from {width}x{height} to {new_width}x{new_height} to fit API input limits.")
        return img.resize((new_width, new_height), Image.Resampling.LANCZOS)  # High-quality resize
    return img

# Function to limit the upscaled image size to fit within API output limits
def adjust_upscaled_size(width, height, max_pixels=4194304):
    aspect_ratio = width / height
    if width * height > max_pixels:
        new_width = int((max_pixels * aspect_ratio) ** 0.5)
        new_height = int(new_width / aspect_ratio)
        print(f"Adjusting upscale size from {width}x{height} to {new_width}x{new_height} to fit API output limits.")
        return new_width
    return width

# Function to upscale an individual image
def upscale_image(input_image_path, output_image_path):
    # Open the image using PIL.Image
    img = Image.open(input_image_path)

    # Resize image if it's too large for the API
    img = resize_image_if_needed(img)

    # Limit the upscaled width to ensure the final image fits within the API output limits
    width, height = img.size
    upscale_width = adjust_upscaled_size(width, height)

    # Create the upscaling request using the Stability AI client
    answers = stability_api.upscale(
        init_image=img,  # Pass the resized image object (not bytes)
        width=upscale_width  # Set only the width (height will be adjusted to maintain aspect ratio)
    )

    # Process the response and save the upscaled image
    for resp in answers:
        for artifact in resp.artifacts:
            if artifact.finish_reason == generation.FILTER:
                print("Image filtered.")
            if artifact.type == generation.ARTIFACT_IMAGE:
                # Convert the bytes returned by the API to an image
                upscaled_img = Image.open(BytesIO(artifact.binary))
                # Save the upscaled image
                upscaled_img.save(output_image_path, quality=95)  # Save at high quality
                print(f"Upscaled image saved to {output_image_path}")

# Function to upscale all images in a folder
def upscale_images_in_folder(input_folder, output_folder):
    # Ensure output folder exists
    os.makedirs(output_folder, exist_ok=True)
    
    # Loop through all image files in the input folder
    for filename in os.listdir(input_folder):
        if filename.endswith((".png", ".jpg", ".jpeg")):  # Add other formats if needed
            input_image_path = os.path.join(input_folder, filename)
            output_image_path = os.path.join(output_folder, filename)

            print(f"Upscaling {filename}...")
            upscale_image(input_image_path, output_image_path)

# Example usage
input_folder = "/Users/kadegreenland/Desktop/Module Images/Module 3"  # Replace with the path to your input folder
output_folder = "/Users/kadegreenland/Desktop/Module Images/Upscaled"  # Replace with the path to your output folder

upscale_images_in_folder(input_folder, output_folder)        

  1. Running the Script: Once the script was ready, I ran it from Terminal:

python3 upscale_images.py        

The script processed all 30 images, upscaling each one and saving them in a new folder. What would have taken hours manually was done in minutes, all thanks to the combination of ChatGPT and Stability AI.

Here’s a short Loom of the process


Why This Matters for Content Creators

If you’re dealing with a folder full of low-resolution images, this approach is a huge time-saver. You can batch upscale your images quickly and automatically without uploading them to an online service one by one. This is perfect for anyone who needs to upscale multiple images for content projects.

What You’ll Need:

  • A folder with your low-resolution images.
  • Stability AI for upscaling.
  • ChatGPT (or another AI tool) to help generate the script, or use the one provided above.

By automating this process, you can focus on creating high-quality content, rather than spending hours upscaling images manually.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了