Skip to content

Latest commit

 

History

History
478 lines (324 loc) · 18.6 KB

File metadata and controls

478 lines (324 loc) · 18.6 KB

建立圖像生成應用程式

建立圖像生成應用程式

大型語言模型(LLMs)不僅僅能生成文字,還可以根據文字描述生成圖像。圖像作為一種表達方式,在醫療技術、建築、旅遊、遊戲開發等多個領域都非常有用。在本章中,我們將探討兩個最受歡迎的圖像生成模型:DALL-E 和 Midjourney。

簡介

在本課程中,我們將涵蓋以下內容:

  • 圖像生成及其重要性。
  • DALL-E 和 Midjourney,它們是什麼以及如何運作。
  • 如何建立一個圖像生成應用程式。

學習目標

完成本課程後,您將能夠:

  • 建立一個圖像生成應用程式。
  • 使用元提示為您的應用程式定義邊界。
  • 使用 DALL-E 和 Midjourney。

為什麼要建立圖像生成應用程式?

圖像生成應用程式是一個探索生成式人工智能能力的好方法。它們可以用於以下用途,例如:

  • 圖像編輯和合成。您可以生成各種用途的圖像,例如圖像編輯和圖像合成。

  • 應用於多個行業。它們還可以用於生成適用於醫療技術、旅遊、遊戲開發等多個行業的圖像。

情境:Edu4All

在本課程中,我們將繼續與我們的初創公司 Edu4All 合作。學生將為他們的評估創建圖像,具體創作什麼圖像由學生自行決定,例如他們可以為自己的童話故事創作插圖,或者創建一個新角色,幫助他們可視化自己的想法和概念。

例如,如果 Edu4All 的學生在課堂上學習紀念碑,他們可以生成以下圖像:

Edu4All 初創公司,紀念碑課堂,艾菲爾鐵塔

使用以下提示:

"清晨陽光下,狗站在艾菲爾鐵塔旁邊"

DALL-E 和 Midjourney 是什麼?

DALL-EMidjourney 是兩個最受歡迎的圖像生成模型,它們允許您使用提示生成圖像。

DALL-E

首先介紹 DALL-E,它是一個生成式人工智能模型,可以根據文字描述生成圖像。

DALL-E 是兩個模型的結合:CLIP 和擴散注意力

  • CLIP 是一個模型,可以從圖像和文字中生成嵌入,即數據的數字表示。

  • 擴散注意力 是一個模型,可以從嵌入中生成圖像。DALL-E 是基於圖像和文字數據集進行訓練的,可以用來根據文字描述生成圖像。例如,DALL-E 可以用來生成戴著帽子的貓或有莫霍克髮型的狗的圖像。

Midjourney

Midjourney 的工作方式與 DALL-E 類似,它根據文字提示生成圖像。Midjourney 也可以使用像“戴著帽子的貓”或“有莫霍克髮型的狗”這樣的提示來生成圖像。

由 Midjourney 生成的圖像,機械鴿子 圖片來源:維基百科,由 Midjourney 生成的圖像

DALL-E 和 Midjourney 的工作原理

首先,DALL-E。DALL-E 是基於變壓器架構的生成式人工智能模型,採用自回歸變壓器。

自回歸變壓器定義了模型如何根據文字描述生成圖像,它一次生成一個像素,然後使用生成的像素生成下一個像素。通過神經網絡的多層處理,直到圖像完成。

通過這個過程,DALL-E 可以控制生成圖像中的屬性、物件、特徵等。然而,DALL-E 2 和 3 對生成的圖像有更高的控制能力。

建立您的第一個圖像生成應用程式

那麼,建立一個圖像生成應用程式需要什麼呢?您需要以下庫:

  • python-dotenv,強烈建議使用此庫將您的密鑰保存在 .env 文件中,遠離代碼。
  • openai,此庫用於與 OpenAI API 進行交互。
  • pillow,用於在 Python 中處理圖像。
  • requests,幫助您進行 HTTP 請求。

創建並部署 Azure OpenAI 模型

如果尚未完成,請按照 Microsoft Learn 頁面的指示創建 Azure OpenAI 資源和模型。選擇 DALL-E 3 作為模型。

創建應用程式

  1. 創建一個名為 .env 的文件,內容如下:

    AZURE_OPENAI_ENDPOINT=<your endpoint>
    AZURE_OPENAI_API_KEY=<your key>
    AZURE_OPENAI_DEPLOYMENT="dall-e-3"
    

    在 Azure OpenAI Foundry Portal 的“部署”部分找到此信息。

  2. 在名為 requirements.txt 的文件中收集上述庫,如下所示:

    python-dotenv
    openai
    pillow
    requests
    
  3. 接下來,創建虛擬環境並安裝庫:

    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt

    對於 Windows,用以下命令創建並激活虛擬環境:

    python3 -m venv venv
    venv\Scripts\activate.bat
  4. 在名為 app.py 的文件中添加以下代碼:

    import openai
    import os
    import requests
    from PIL import Image
    import dotenv
    from openai import OpenAI, AzureOpenAI
    
    # import dotenv
    dotenv.load_dotenv()
    
    # configure Azure OpenAI service client 
    client = AzureOpenAI(
      azure_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"],
      api_key=os.environ['AZURE_OPENAI_API_KEY'],
      api_version = "2024-02-01"
      )
    try:
        # Create an image by using the image generation API
        generation_response = client.images.generate(
                                prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',
                                size='1024x1024', n=1,
                                model=os.environ['AZURE_OPENAI_DEPLOYMENT']
                              )
    
        # 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()
  • 然後,我們配置 Azure OpenAI 服務客戶端。

    # Get endpoint and key from environment variables
    client = AzureOpenAI(
        azure_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"],
        api_key=os.environ['AZURE_OPENAI_API_KEY'],
        api_version = "2024-02-01"
        )
  • 接下來,我們生成圖像:

    # Create an image by using the image generation API
    generation_response = client.images.generate(
                          prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',
                          size='1024x1024', n=1,
                          model=os.environ['AZURE_OPENAI_DEPLOYMENT']
                        )

    上述代碼返回一個包含生成圖像 URL 的 JSON 對象。我們可以使用該 URL 下載圖像並保存到文件中。

  • 最後,我們打開圖像並使用標準圖像查看器顯示它:

    image = Image.open(image_path)
    image.show()

更詳細的圖像生成過程

讓我們更詳細地看看生成圖像的代碼:

  generation_response = client.images.generate(
                            prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils',
                            size='1024x1024', n=1,
                            model=os.environ['AZURE_OPENAI_DEPLOYMENT']
                        )
  • prompt 是用於生成圖像的文字提示。在這個例子中,我們使用的提示是“兔子騎在馬上,手拿棒棒糖,站在長滿水仙花的霧霾草地上”。
  • size 是生成圖像的大小。在這個例子中,我們生成的圖像大小為 1024x1024 像素。
  • n 是生成的圖像數量。在這個例子中,我們生成了兩張圖像。
  • temperature 是一個控制生成式人工智能模型輸出隨機性的參數。溫度值介於 0 到 1 之間,其中 0 表示輸出是確定性的,1 表示輸出是隨機的。默認值為 0.7。

在下一部分中,我們將探討更多可以對圖像進行的操作。

圖像生成的其他功能

到目前為止,您已經看到如何使用幾行 Python 代碼生成圖像。然而,您還可以對圖像進行更多操作。

您還可以執行以下操作:

  • 進行編輯。通過提供現有圖像的遮罩和提示,您可以修改圖像。例如,您可以在圖像的一部分添加某些元素。想像一下我們的兔子圖像,您可以給兔子添加一頂帽子。方法是提供圖像、遮罩(標識需要更改的區域)以及文字提示來描述需要進行的操作。

注意:這在 DALL-E 3 中不支持。

以下是使用 GPT Image 的示例:

response = client.images.edit(
    model="gpt-image-1",
    image=open("sunlit_lounge.png", "rb"),
    mask=open("mask.png", "rb"),
    prompt="A sunlit indoor lounge area with a pool containing a flamingo"
)
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 上支持。

溫度

溫度是一個控制生成式人工智能模型輸出隨機性的參數。溫度值介於 0 到 1 之間,其中 0 表示輸出是確定性的,1 表示輸出是隨機的。默認值為 0.7。

讓我們通過兩次運行以下提示來看看溫度的作用:

提示: "兔子騎在馬上,手拿棒棒糖,站在長滿水仙花的霧霾草地上"

兔子騎在馬上,手拿棒棒糖,版本 1

現在讓我們再次運行相同的提示,看看是否會生成相同的圖像:

兔子騎在馬上的生成圖像

如您所見,這些圖像相似,但並不完全相同。現在讓我們嘗試將溫度值更改為 0.1,看看會發生什麼:

 generation_response = client.images.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 = client.images.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
    )

現在運行此代碼,您將獲得以下兩張圖像:

  • 溫度 0,版本 1
  • 溫度 0,版本 2

在這裡,您可以清楚地看到這些圖像更加相似。

如何使用元提示為您的應用程式定義邊界

通過我們的演示,我們已經可以為客戶生成圖像。然而,我們需要為應用程式設置一些邊界。

例如,我們不希望生成不適合工作環境或不適合兒童的圖像。

我們可以使用 元提示 來實現這一點。元提示是用於控制生成式人工智能模型輸出的文字提示。例如,我們可以使用元提示來控制輸出,確保生成的圖像適合工作環境或適合兒童。

它是如何工作的?

那麼,元提示是如何工作的呢?

元提示是用於控制生成式人工智能模型輸出的文字提示,它們位於文字提示之前,用於控制模型的輸出,並嵌入到應用程式中以控制模型的輸出。將提示輸入和元提示輸入封裝在一個文字提示中。

以下是一個元提示的示例:

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
from openai import AzureOpenAI
# import dotenv
dotenv.load_dotenv()

# Get endpoint and key from environment variables
client = AzureOpenAI(
  azure_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"],
  api_key=os.environ['AZURE_OPENAI_API_KEY'],
  api_version = "2024-02-01"
  )


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 = client.images.generate(
        prompt=prompt,    # Enter your prompt text here
        size='1024x1024',
        n=1,
    )
    # 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.BadRequestError as err:
    print(err)

幹得好!繼續學習

完成這節課後,請查看我們的生成式 AI 學習合集,繼續提升您的生成式 AI 知識!

前往第10課,我們將探討如何使用低代碼構建 AI 應用程式


免責聲明
此文件已使用人工智能翻譯服務 Co-op Translator 進行翻譯。儘管我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應被視為權威來源。對於重要信息,建議使用專業人工翻譯。我們不對因使用此翻譯而引起的任何誤解或誤釋承擔責任。