Skip to main content
In this tutorial, you’ll learn how to use DALL·E 2’s image masking feature to edit an existing picture by defining a masked region and supplying a text prompt. This approach is perfect for seamlessly replacing objects, changing backgrounds, or adding new elements to your images.

Prerequisites

  • Python 3.7+
  • The openai Python package (pip install openai)
  • An OpenAI API key
Make sure you’ve exported your API key as an environment variable:

1. Install and Authenticate

Begin by installing the client library and initializing your API key in Python:

2. Prepare Your Images

You need three files:
  1. Original image (with the object you want to replace)
  2. Base image (same image after removing the object)
  3. Mask image (a transparent PNG that marks the area to edit)

3. Perform the Edit

Use the create_edit endpoint to fill the masked area based on your prompt:

4. Generate Multiple Variations

If you’d like several options, increase n and iterate through the results:
Requesting a large number of edits or very high resolutions may incur higher usage costs. Monitor your API usage dashboard.

5. Parameter Reference

6. Generate Image Variations

Beyond masking, DALL·E 2 can also create variations of a single image without any prompt:
For full details on both endpoints, see the OpenAI Image API Reference.

Watch Video

Practice Lab