大型語言模型不只會產生文字,也能從文字描述生成圖像。圖像作為一種媒介,在醫療科技、建築、旅遊、遊戲開發等多個領域都非常有用。本章節將介紹兩個最受歡迎的圖像生成模型:DALL-E 和 Midjourney。
本課程將涵蓋:
- 圖像生成及其用途。
- DALL-E 和 Midjourney 是什麼,以及它們的運作原理。
- 如何建立一個圖像生成應用程式。
完成本課程後,你將能夠:
- 建立一個圖像生成應用程式。
- 使用元提示(meta prompts)為應用程式設定界限。
- 使用 DALL-E 和 Midjourney。
圖像生成應用程式是探索生成式 AI 能力的絕佳方式。它們可以用於:
-
圖像編輯與合成。你可以生成各種用途的圖像,例如圖像編輯和合成。
-
應用於多個產業。也能用於醫療科技、旅遊、遊戲開發等多個產業的圖像生成。
在本課程中,我們將繼續與創業公司 Edu4All 合作。學生們會為他們的評估創作圖像,具體內容由學生決定,可能是他們自己童話故事的插畫、故事中的新角色,或幫助他們視覺化想法和概念。
例如,若 Edu4All 的學生在課堂上研究紀念碑,他們可能會生成如下圖像:
使用的提示語可能是:
「清晨陽光下,埃菲爾鐵塔旁的一隻狗」
DALL-E 和 Midjourney 是兩個最受歡迎的圖像生成模型,能透過提示語生成圖像。
先從 DALL-E 開始,它是一個從文字描述生成圖像的生成式 AI 模型。
-
CLIP 是一個從圖像和文字中產生嵌入向量(數值表示)的模型。
-
Diffused attention 是一個從嵌入向量生成圖像的模型。DALL-E 在圖像和文字資料集上訓練,能根據文字描述生成圖像。例如,DALL-E 可以生成戴帽子的貓或莫霍克髮型的狗的圖像。
Midjourney 的運作方式與 DALL-E 類似,能根據文字提示生成圖像。Midjourney 也能用提示語如「戴帽子的貓」或「莫霍克髮型的狗」來生成圖像。
圖片來源 Wikipedia,由 Midjourney 生成
首先是 DALL-E。DALL-E 是基於 transformer 架構的生成式 AI 模型,採用 自回歸 transformer。
自回歸 transformer 定義了模型如何從文字描述生成圖像,它一次生成一個像素,然後利用已生成的像素來生成下一個像素。透過神經網絡的多層處理,直到圖像完成。
透過這個過程,DALL-E 能控制圖像中的屬性、物件、特徵等。不過,DALL-E 2 和 3 對生成圖像的控制力更強。
那麼,建立一個圖像生成應用程式需要什麼?你需要以下函式庫:
- python-dotenv,強烈建議使用此函式庫將機密資訊保存在 .env 檔案中,避免直接寫在程式碼裡。
- openai,用來與 OpenAI API 互動的函式庫。
- pillow,用於在 Python 中處理圖像。
- requests,協助發送 HTTP 請求。
-
建立一個 .env 檔案,內容如下:
AZURE_OPENAI_ENDPOINT=<your endpoint> AZURE_OPENAI_API_KEY=<your key>你可以在 Azure 入口網站的「金鑰與端點」區段找到這些資訊。
-
將上述函式庫列在 requirements.txt 檔案中,如下:
python-dotenv openai pillow requests -
接著,建立虛擬環境並安裝函式庫:
python3 -m venv venv source venv/bin/activate pip install -r requirements.txtWindows 使用者可用以下指令建立並啟動虛擬環境:
python3 -m venv venv venv\Scripts\activate.bat
-
在 app.py 檔案中加入以下程式碼:
import openai import os import requests from PIL import Image import dotenv # import dotenv dotenv.load_dotenv() # Get endpoint and key from environment variables openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] openai.api_key = os.environ['AZURE_OPENAI_API_KEY'] # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) openai.api_version = '2023-06-01-preview' openai.api_type = 'azure' try: # Create an image by using the image generation API generation_response = openai.Image.create( prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here size='1024x1024', n=2, temperature=0, ) # Set the directory for the stored image image_dir = os.path.join(os.curdir, 'images') # If the directory doesn't exist, create it if not os.path.isdir(image_dir): os.mkdir(image_dir) # Initialize the image path (note the filetype should be png) image_path = os.path.join(image_dir, 'generated-image.png') # Retrieve the generated image image_url = generation_response["data"][0]["url"] # extract image URL from response generated_image = requests.get(image_url).content # download the image with open(image_path, "wb") as image_file: image_file.write(generated_image) # Display the image in the default image viewer image = Image.open(image_path) image.show() # catch exceptions except openai.InvalidRequestError as err: print(err)
讓我們解釋這段程式碼:
-
首先,我們匯入所需的函式庫,包括 OpenAI、dotenv、requests 和 Pillow。
import openai import os import requests from PIL import Image import dotenv
-
接著,我們從 .env 檔案載入環境變數。
# import dotenv dotenv.load_dotenv()
-
然後,設定 OpenAI API 的端點、金鑰、版本和類型。
# Get endpoint and key from environment variables openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] openai.api_key = os.environ['AZURE_OPENAI_API_KEY'] # add version and type, Azure specific openai.api_version = '2023-06-01-preview' openai.api_type = 'azure'
-
接著,我們生成圖像:
# Create an image by using the image generation API generation_response = openai.Image.create( prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here size='1024x1024', n=2, temperature=0, )
上述程式碼會回傳一個 JSON 物件,包含生成圖像的 URL。我們可以用這個 URL 下載圖像並儲存成檔案。
-
最後,我們開啟圖像並用標準圖像檢視器顯示:
image = Image.open(image_path) image.show()
讓我們更仔細看看生成圖像的程式碼:
generation_response = openai.Image.create(
prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here
size='1024x1024',
n=2,
temperature=0,
)- prompt 是用來生成圖像的文字提示。這裡使用的提示是「兔子騎馬,手持棒棒糖,站在長滿水仙花的霧氣草地上」。
- size 是生成圖像的尺寸,這裡是 1024x1024 像素。
- n 是生成圖像的數量,這裡是兩張。
- temperature 是控制生成式 AI 輸出隨機性的參數,介於 0 到 1 之間,0 表示輸出是確定性的,1 表示輸出是隨機的。預設值是 0.7。
接下來我們會介紹更多圖像相關的功能。
到目前為止,你已經看到如何用幾行 Python 程式碼生成圖像。但圖像還能做更多事。
你還可以:
-
進行編輯。透過提供現有圖像、遮罩和提示語,你可以修改圖像。例如,你可以在圖像的某部分加上東西。想像我們的兔子圖像,你可以幫兔子戴上帽子。做法是提供原始圖像、一個標示要修改區域的遮罩,以及描述要做什麼的文字提示。
response = openai.Image.create_edit( image=open("base_image.png", "rb"), mask=open("mask.png", "rb"), prompt="An image of a rabbit with a hat on its head.", n=1, size="1024x1024" ) image_url = response['data'][0]['url']
原始圖像只有兔子,最終圖像則是兔子戴上了帽子。
-
創造變體。你可以拿現有圖像,要求生成多個變體。要創造變體,你需要提供圖像和文字提示,程式碼如下:
response = openai.Image.create_variation( image=open("bunny-lollipop.png", "rb"), n=1, size="1024x1024" ) image_url = response['data'][0]['url']
注意,這功能目前只支援 OpenAI。
溫度是控制生成式 AI 輸出隨機性的參數,介於 0 到 1 之間,0 表示輸出是確定性的,1 表示輸出是隨機的。預設值是 0.7。
讓我們透過以下提示語執行兩次,看看溫度的效果:
提示語:「兔子騎馬,手持棒棒糖,站在長滿水仙花的霧氣草地上」
現在再執行一次相同提示語,看看是否會得到相同圖像:
如你所見,兩張圖像相似但不完全相同。接著,我們將溫度調整為 0.1,看看會發生什麼:
generation_response = openai.Image.create(
prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here
size='1024x1024',
n=2
)我們試著讓輸出更確定性。從剛才兩張圖像可見,第一張有兔子,第二張有馬,差異很大。
因此,我們修改程式碼,將溫度設為 0,如下:
generation_response = openai.Image.create(
prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here
size='1024x1024',
n=2,
temperature=0
)執行後,你會得到以下兩張圖像:
你可以明顯看到兩張圖像更為相似。
透過我們的示範,已能為客戶生成圖像,但我們需要為應用程式設定一些界限。
例如,我們不希望生成不適合工作場合或兒童觀看的圖像。
這可以透過 元提示(metaprompts)達成。元提示是用來控制生成式 AI 輸出內容的文字提示。例如,我們可以用元提示確保生成的圖像適合工作場合或兒童觀看。
元提示是放在主要提示語之前的文字提示,用來控制模型的輸出,並嵌入應用程式中以管理生成結果。它將提示輸入和元提示合併成一個完整的文字提示。
以下是一個元提示的範例:
You are an assistant designer that creates images for children.
The image needs to be safe for work and appropriate for children.
The image needs to be in color.
The image needs to be in landscape orientation.
The image needs to be in a 16:9 aspect ratio.
Do not consider any input from the following that is not safe for work or appropriate for children.
(Input)
接著,看看我們如何在示範中使用元提示。
disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult"
meta_prompt =f"""You are an assistant designer that creates images for children.
The image needs to be safe for work and appropriate for children.
The image needs to be in color.
The image needs to be in landscape orientation.
The image needs to be in a 16:9 aspect ratio.
Do not consider any input from the following that is not safe for work or appropriate for children.
{disallow_list}
"""
prompt = f"{meta_prompt}
Create an image of a bunny on a horse, holding a lollipop"
# TODO add request to generate image從上述提示可見,所有生成的圖像都會考慮元提示的限制。
我們在課程一開始介紹了 Edu4All,現在是時候讓學生為他們的評估生成圖像。
學生將為評估創作包含紀念碑的圖像,具體哪些紀念碑由學生自行決定。學生被鼓勵發揮創意,將這些紀念碑置於不同的情境中。
以下是一個可能的解答:
import openai
import os
import requests
from PIL import Image
import dotenv
# import dotenv
dotenv.load_dotenv()
# Get endpoint and key from environment variables
openai.api_base = "<replace with endpoint>"
openai.api_key = "<replace with api key>"
# Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only)
openai.api_version = '2023-06-01-preview'
openai.api_type = 'azure'
disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult"
meta_prompt = f"""You are an assistant designer that creates images for children.
The image needs to be safe for work and appropriate for children.
The image needs to be in color.
The image needs to be in landscape orientation.
The image needs to be in a 16:9 aspect ratio.
Do not consider any input from the following that is not safe for work or appropriate for children.
{disallow_list}"""
prompt = f"""{meta_prompt}
Generate monument of the Arc of Triumph in Paris, France, in the evening light with a small child holding a Teddy looks on.
""""
try:
# Create an image by using the image generation API
generation_response = openai.Image.create(
prompt=prompt, # Enter your prompt text here
size='1024x1024',
n=2,
temperature=0,
)
# Set the directory for the stored image
image_dir = os.path.join(os.curdir, 'images')
# If the directory doesn't exist, create it
if not os.path.isdir(image_dir):
os.mkdir(image_dir)
# Initialize the image path (note the filetype should be png)
image_path = os.path.join(image_dir, 'generated-image.png')
# Retrieve the generated image
image_url = generation_response["data"][0]["url"] # extract image URL from response
generated_image = requests.get(image_url).content # download the image
with open(image_path, "wb") as image_file:
image_file.write(generated_image)
# Display the image in the default image viewer
image = Image.open(image_path)
image.show()
# catch exceptions
except openai.InvalidRequestError as err:
print(err)完成本課程後,歡迎參考我們的生成式 AI 學習資源集,持續提升你的生成式 AI 知識!
接著前往第 10 課,我們將探討如何用低程式碼建立 AI 應用程式
免責聲明:
本文件由 AI 翻譯服務 Co-op Translator 進行翻譯。雖然我們致力於確保準確性,但請注意自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應被視為權威來源。對於重要資訊,建議採用專業人工翻譯。我們不對因使用本翻譯而引起的任何誤解或誤釋承擔責任。





