Generate images using OpenAI models in Python
Learn how to generate images using OpenAI DALL-E 3 model in Python. The notebook covers generating an image with specific parameters, saving it locally and displaying it using the PIL library.
MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.
The cell with all necessary import:
# import packages
import os
from dotenv import load_dotenv
from openai import OpenAI, AuthenticationError
import requests
from PIL import Image
The OpenAI client connection:
# load .env file
load_dotenv()
# get api key from environment
api_key = os.environ["OPENAI_KEY"]
# create OpenAI client
def create_client(api_key):
try:
client = OpenAI(api_key=api_key)
client.models.list()
return client
except AuthenticationError:
print("Incorrect API")
return None
client = create_client(api_key)
You can generate an image using below recipe:
# create request
response = client.images.generate(
model="dall-e-3",
prompt="Muscular tiger wearing a tank-top and doing the biceps curl.",
size="1024x1024",
quality="standard",
n=1
)
# save response
res = requests.get(response.data[0].url, stream=True)
# set image path
image = os.path.join(r"../../../../demo", "ai-image.png")
# save and display image
if res.status_code == 200:
with open(image, "wb") as file:
for chunk in res.iter_content(1024):
file.write(chunk)
with Image.open(image) as i:
display(i)
else:
print("Failed to retrieve the image. Status code:", response.status_code)
Except the prompt, you can also modify the size and quality of the output image. Check another example:
# create request
response = client.images.generate(
model="dall-e-3",
prompt="Muscular tiger and lion doing arm wrestling in the park",
size="1792x1024",
quality="hd",
n=1
)
# save response
res = requests.get(response.data[0].url, stream=True)
# set image path
image = os.path.join(r"../../../../demo", "ai-image2.png")
# save and display image
if res.status_code == 200:
with open(image, "wb") as file:
for chunk in res.iter_content(1024):
file.write(chunk)
with Image.open(image) as i:
display(i)
else:
print("Failed to retrieve the image. Status code:", response.status_code)
REMEMBER! Changing the size and quality of the output image may affect the price. Check the OpenAI API Pricing
Conclusions
With this recipe you can easily generate images using AI which is useful in many cases like creating sales offers. Stay with us to learn much more. :)
Recipes used in the python-generate-image.ipynb
All code recipes used in this notebook are listed below. You can click them to check their documentation.
Packages used in the python-generate-image.ipynb
List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.
openai>=1.35.14
python-dotenv>=1.0.1
pillow>=10.2.0
requests>=2.31.0
Similar notebooks
List of similar Python notebooks, so you can find more inspiration ๐
Connection with OpenAI Client using Python
OpenAI Chat Completion in Python Notebook
How to search the cosine similarity using ...
How to generate text embeddings using OpenAI ...
Generate embeddings for whole files using ...
Generate images using OpenAI models in Python
Transcribe the speech using OpenAI in Python
Translate the speech using OpenAI in Python
Generate speech from the given text using ...
OpenAI vision with local images in Python
OpenAI vision with URL images in Python
Build RAG App using OpenAI in Python