DEV Community

Shilleh
Shilleh

Posted on • Updated on

How to Edit Images with OpenAI in Python

Example of Edit with OpenAI

You can actually make some cool edits to images with the OpenAI API in Python. It is initially free to use and easy to set up in Python.

Some important things to note:

  • You need a square image and a square mask.
  • You can create a mask of an image here using this free online tool. It only allows a square mask.
  • You need to describe the image itself and what you want in the mask, the AI needs to have some context on the existing image, or else the edit will not work.
  • The image I found online was in “Palette” mode, so I needed to initially convert it to RGB by using the Pillow library in Python. You can uncomment the code below if you are having Palette issues.

Here is the code:

import openai

# from PIL import Image

import constants

# Set up the OpenAI API client
openai.api_key = constants.API_KEY

# Image.open("dalle-2 examples/cute_cat.png").convert("RGB").save(
#     "dalle-2 examples/cute_cat.png"
# )
# Generate a image from ChatGPT
response = openai.Image.create_edit(
    image=open("dalle-2 examples/cute_cat.png", "rb"),
    mask=open("dalle-2 examples/mask.png", "rb"),
    prompt="A black and white cat with a red ball",
    n=1,
    size="512x512",
)
image_url = response["data"][0]["url"]

# Print the response
print(image_url) 
Enter fullscreen mode Exit fullscreen mode

Here is the video, would appreciate a subscription if you learn something new!

Top comments (0)