OpenAI, ChatGPT, DALL·E 2, create image from text prompt
This post is describe how to generate image from text prompt.

How to use OpenAI
- Go to the website openai.com and create user profile.
- Generate new OPENAI_API_KEY.
- Use public API
DALL·E 2
DALL·E 2 is a revolutionary artificial intelligence system that can generate realistic images and artwork based on descriptions provided in natural language.
Install OpenAI CLI
OpenAI CLI create image
|
|

OpenAI Python script create image
Some fun Python code to work with Rick and Morty and OpenAI Image API.
1import shutil
2import pathlib
3import openai
4import requests # pip install requests
5from PIL import Image
6
7HOME = str(pathlib.Path.home())
8openai.api_key = "MY_SECRET_KEY"
9
10def save_image(url, name):
11 r = requests.get(url, stream=True)
12 if r.status_code == 200:
13 with open(f'{HOME}/Downloads/rick/{name}.png', 'wb') as f:
14 r.raw.decode_content = True
15 shutil.copyfileobj(r.raw, f)
16
17
18image_urls = []
19prompts = [
20 "Rick and Morty stuck in a time loop",
21 "Rick and Morty sitting on a couch, looking frustrated",
22]
23for prompt in prompts:
24 response = openai.Image.create(
25 prompt=prompt,
26 n=4,
27 size="1024x1024"
28 )
29 for data in response['data']:
30 image_urls.append(data['url'])
31
32for i, url in enumerate(image_urls):
33 save_image(url, i)








API
openai.Image.create_edit
has some limitation, so we need to compress input image. Input images:


1foo = Image.open(f"{HOME}/Downloads/rick/image_edit.png")
2foo = foo.resize((1080,1080),Image.LANCZOS)
3foo.save(f"{HOME}/Downloads/rick/image_edit2.png", optimize=True, quality=75)
4
5foo1 = Image.open(f"{HOME}/Downloads/rick/image_mask.png")
6foo1 = foo1.resize((1080,1080),Image.LANCZOS)
7foo1.save(f"{HOME}/Downloads/rick/image_mask2.png", optimize=True, quality=75)
Size optimized images:


and then we can make API call
1image_urls2 = []
2response = openai.Image.create_edit(
3 image=open(f"{HOME}/Downloads/rick/image_edit2.png", "rb"),
4 mask=open(f"{HOME}/Downloads/rick/image_mask2.png", "rb"),
5 prompt="Rick and Morty stuck in a time loop",
6 n=4,
7)
8for data in response['data']:
9 image_urls2.append(data['url'])
10
11for i, url in enumerate(image_urls2):
12 save_image(url, i)




Result is not so great but if you spend some time to create good prompt, you will get better one.
Links