Mastering Generative AI with OpenAI

Generating Images

Demo Image Variations

In this tutorial, you’ll learn how to generate multiple variations of an existing image using the OpenAI DALL·E API. By the end, you’ll be able to:

  • Load and preview a source image
  • Call the DALL·E variations endpoint
  • Render the generated images

Prerequisites

  • Python 3.6+
  • Install the OpenAI Python library:
pip install openai
  • Set your API key as an environment variable:
export OPENAI_API_KEY="your_api_key_here"

1. Import Modules and Configure the API Key

Begin by importing the necessary modules and loading your API key:

import openai
import os
from IPython.display import Image, display

openai.api_key = os.getenv("OPENAI_API_KEY")

2. Load and Display the Source Image

Use IPython’s display utilities to preview the original asset:

display(Image(filename='./images/lion-cub.png'))

This shows a lion and its cub.

3. Generate Three Variations

Call the DALL·E variation endpoint, specifying the image file, output size, and number of results:

response = openai.Image.create_variation(
    image=open('./images/lion-cub.png', 'rb'),
    size='512x512',
    n=3
)

Tip

You can modify the size or the n parameter to control the resolution and the number of variations returned.

4. Render the Generated Variations

Display each variation using the URLs returned in the response:

# Variation 1
display(Image(url=response['data'][0]['url']))

# Variation 2
display(Image(url=response['data'][1]['url']))

# Variation 3
display(Image(url=response['data'][2]['url']))

Each variation offers a unique composition or style. Experiment with different source images or parameters to explore new creative directions.

Summary of Steps

StepDescriptionExample Code
Import & AuthenticateLoad libraries and set API keyopenai.api_key = os.getenv("OPENAI_API_KEY")
Preview Source ImageDisplay the original imagedisplay(Image(...))
Request VariationsGenerate n new images with specified sizeopenai.Image.create_variation(...)
Render OutputsShow each variation using returned URLsdisplay(Image(url=...))

Next Steps

Now that you’ve created image variations, consider exploring other OpenAI offerings:

References

Watch Video

Watch video content

Practice Lab

Practice lab

Previous
Demo Image Masking