资讯动态

构建图像生成应用:基于 DALL-E 与 GPT Image 的文本到图像实战指南(Generative AI for Beginners 第 9 课)

发布时间:2026/9/10 2:47:21 来源:尧图企业网站定制
构建图像生成应用基于 DALL-E 与 GPT Image 的文本到图像实战指南Generative AI for Beginners 第 9 课【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners本指南以《Generative AI for Beginners》课程第 9 课translations/he/09-building-image-applications/README.md英文原版见 09-building-image-applications/README.md为骨架展开结合仓库内 Python、TypeScript 等真实示例代码进行深化。你将掌握图像生成模型DALL-E / Midjourney的基本原理、基于 Azure OpenAI 用几行 Python 生成并保存图像、用temperature控制输出随机性、用图像编辑与变体能力扩展应用以及用元提示词meta prompt为应用设定安全边界。学习目标完成本课后你将能够构建一个完整的图像生成应用使用元提示词为应用定义内容边界熟练使用 DALL-E / GPT Image 等图像生成模型。为什么构建图像生成应用大语言模型LLM的能力远不止文本生成——它同样可以从文本描述生成图像。图像作为模态modality在许多领域都极具价值包括图像编辑与合成为多种场景生成图像例如照片编辑、图像合成跨行业应用医疗科技MedTech、建筑、旅游、游戏开发等领域都可以借助文本到图像能力快速产出视觉素材。图像生成应用也是探索生成式 AI 能力边界的最佳入口输入一个自然语言提示词模型就能返回一张全新的图片。教学场景Edu4All本课继续沿用课程贯穿的虚构初创公司Edu4All场景学生需要为自己的评估项目生成配图——可以是自己童话故事的插图、故事的新角色也可以用来可视化自己的想法与概念。例如当课堂上学习地标建筑主题时学生可以生成这样一张图使用的提示词类似Dog next to Eiffel Tower in early morning sunlight清晨阳光下、埃菲尔铁塔旁的狗认识 DALL-E 与 MidjourneyDALL-E 与 Midjourney 是当下最流行的两个图像生成模型它们都允许用户通过提示词生成图像。DALL-EDALL-E 是一个从文本描述生成图像的生成式 AI 模型。从模型结构上看DALL-E 是两个模型的组合CLIP从图像和文本中生成 embedding数据的数值化表示的模型Diffused attention扩散注意力从 embedding 生成图像的模型。DALL-E 在海量的图像-文本配对数据集上训练因此可以完成戴帽子的猫莫霍克发型的狗这类跨模态生成任务。MidjourneyMidjourney 的工作方式与 DALL-E 类似输入文本提示词输出图像同样支持戴帽子的猫莫霍克发型的狗等提示词。DALL-E 的工作原理自回归 TransformerDALL-E 是基于 Transformer 架构的生成式 AI 模型其核心是自回归 Transformerautoregressive transformer。所谓自回归指的是模型的生成方式一次只生成一个像素然后用已生成的像素预测下一个像素如此反复经过神经网络的多层计算直到整幅图像完成。在这个过程中DALL-E 能够控制生成图像的属性、对象、特征等要素。而到了 DALL-E 2、DALL-E 3 乃至当前的 gpt-image-1模型对生成结果的控制粒度更细能力也更强。构建你的第一个图像生成应用构建一个图像生成应用需要哪些库本课给出的基础依赖如下见 09-building-image-applications/requirements.txt库用途python-dotenv强烈推荐把密钥等机密信息放在.env文件中与代码隔离openai与 OpenAI / Azure OpenAI API 交互的官方客户端pillow在 Python 中处理打开、显示、保存图像requests发起 HTTP 请求用于下载生成的图像创建并部署 Azure OpenAI 模型如果尚未完成请先在 Azure OpenAI 门户中创建资源与模型部署。请选择gpt-image-1作为模型当前新一代 Azure OpenAI 图像模型DALL-E 3 已属旧版新部署不再提供部署名称需要记住稍后填入环境变量。说明仓库中的 OpenAI 直连示例 oai-app.py 仍使用modeldall-e-3调用 OpenAI API而 Azure OpenAI 侧则以gpt-image-1为当前推荐模型见 README.md。第一步创建.env文件AZURE_OPENAI_ENDPOINTyour endpoint AZURE_OPENAI_API_KEYyour key AZURE_OPENAI_DEPLOYMENTgpt-image-1这些信息可以在 Azure OpenAI Foundry 门户中对应资源的Deployments部署部分找到。第二步整理依赖文件requirements.txtpython-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完整代码将以下代码保存为app.py对应仓库中的 aoai-app.pyimport 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_keyos.environ[AZURE_OPENAI_API_KEY], api_version 2024-10-21 ) try: # Create an image by using the image generation API generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1, modelos.environ[AZURE_OPENAI_DEPLOYMENT] ) # Set the directory for the stored image image_dir os.path.join(os.curdir, images) # If the directory doesnt 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)代码逐段解析导入库引入 OpenAI 客户端、dotenv、requests 与 Pillowimport openai import os import requests from PIL import Image import dotenv加载环境变量从.env文件读取配置dotenv.load_dotenv()配置 Azure OpenAI 客户端azure_endpoint与api_key均从环境变量读取api_version使用2024-10-21具体版本以 Microsoft Foundry 文档中你的模型所要求的 API 版本为准仓库代码 aoai-app.py 中亦有此注释client AzureOpenAI( azure_endpoint os.environ[AZURE_OPENAI_ENDPOINT], api_keyos.environ[AZURE_OPENAI_API_KEY], api_version 2024-10-21 )生成图像调用client.images.generate响应是一个 JSON 对象包含生成图像的 URL随后用 requests 下载并写入本地文件generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1, modelos.environ[AZURE_OPENAI_DEPLOYMENT] ) image_url generation_response.data[0].url generated_image requests.get(image_url).content显示图像用 Pillow 打开并调用系统默认查看器展示image Image.open(image_path) image.show()仓库中 aoai-app.py 的实现还额外使用json.loads(result.model_dump_json())把响应对象序列化为 JSON 后取值并引入BadRequestError异常捕获OpenAI 直连版本 oai-app.py 则为 HTTP 下载增加了 30 秒超时与raise_for_status()校验这些都是在生产环境中值得借鉴的健壮性写法。生成参数详解generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1, modelos.environ[AZURE_OPENAI_DEPLOYMENT] )prompt用于生成图像的文本提示词。本例为 Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils马上的兔子举着棒棒糖在长满水仙花的雾蒙蒙草地上。size生成图像的尺寸。本例为1024x1024像素。n生成的图像数量。本例为1即生成一张。temperature控制生成式 AI 模型输出的随机性取值在 0~1 之间0表示输出趋于确定性1表示输出趋于随机默认值为0.7。需要说明仓库中基于gpt-image-1的示例aoai-app.py、main.ts均未显式传入temperature参数说明该参数的支持情况因模型而异下文关于temperature的实验来自课程文档对经典图像生成 API 的讲解。图像生成的进阶能力除了文生图还可以对已有图像做更多操作。图像编辑Edit提供一张现有图像、一张掩码图mask标记需要修改的区域和一个文本提示词即可修改图像。例如给兔子戴上帽子提供兔子图像、标注帽子区域的掩码、以及给兔子加一顶帽子的提示词。注意图像编辑在 DALL-E 3 中不受支持需使用支持该能力的模型如 gpt-image-1。使用 GPT Image 的编辑示例response client.images.edit( modelgpt-image-1, imageopen(sunlit_lounge.png, rb), maskopen(mask.png, rb), promptA sunlit indoor lounge area with a pool containing a flamingo ) image_url response.data[0].url基底图像只有带泳池的休闲厅而最终图像中会出现一只火烈鸟——这就是图像 掩码 提示词三段式编辑的威力。创建变体Variation变体是指提供一张现有图像让模型生成它的多个变体。调用方式为传入图像文件即可response client.images.create_variation( imageopen(bunny-lollipop.png, rb), n1, size1024x1024 ) image_url response.data[0].url注意变体功能目前仅在 OpenAI 的 DALL-E 2 模型上受支持gpt-image-1不支持。仓库中的 aoai-app-variation.py 展示了完整的变体流程先读取images/generated-image.png调用client.images.create_variation再将结果保存为generated_variation.png。temperature 温度参数实验温度参数控制输出随机性值越低多次生成的结果越接近值越高结果差异越大。默认值0.7。用同一提示词连续运行两次默认温度Prompt: Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils再次运行同一提示词结果不会完全相同可以看到两张图相似但并不相同——这正是随机性的体现。把温度降到 0让输出更确定把temperature显式设为0generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, # Enter your prompt text here size1024x1024, n2, temperature0 )运行后得到的两张图可以明显看到temperature0时两张图之间的相似度远高于默认温度下生成的图。因此需要可复现、风格一致的结果时应调低温度需要多样化创意时可保持或调高温度。用元提示词Meta Prompt为应用设定边界demo 已经能为客户生成图像了但我们还需要为应用设定内容边界——例如不希望生成不适合工作场合、不适合儿童观看的图像。实现手段就是元提示词meta prompt它是用于控制生成式 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)在 demo 中组合元提示词课程给出了带禁用词清单的完整写法对应仓库 aoai-solution.pydisallow_list swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult meta_prompt fYou 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从上述代码可以看到所有生成请求都会先经过元提示词约束从而保证产出的图像符合适合儿童、适合工作场合、彩色、横向、16:9 比例等要求同时对disallow_list中的敏感内容一律不予考虑。作业让学生用起来回到 Edu4All 场景现在轮到你让学生为自己的评估项目生成图像了。任务要求如下学生需要生成包含地标建筑monuments的评估配图具体选择哪些地标由学生自行决定鼓励学生在任务中发挥创意把这些地标放到不同的语境中。参考实现一种可行的解决方案如下完整版见仓库 aoai-solution.pyimport 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_keyos.environ[AZURE_OPENAI_API_KEY], api_version 2024-10-21 ) disallow_list swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult meta_prompt fYou 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( promptprompt, # Enter your prompt text here size1024x1024, n1, ) # Set the directory for the stored image image_dir os.path.join(os.curdir, images) # If the directory doesnt 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)可以看到解题思路就是把元提示词 具体需求巴黎凯旋门、傍晚光线、抱着泰迪熊的孩子拼成一个完整提示词其余流程与基础版完全一致。仓库中的更多示例与变体本课配套代码分散在仓库多个目录可对照阅读09-building-image-applications/python/aoai-app.pyAzure OpenAI 基础文生图示例api_version2024-10-21响应经model_dump_json序列化处理09-building-image-applications/python/oai-app.pyOpenAI 直连版使用dall-e-3模型并在下载图片时加入超时与状态码校验09-building-image-applications/python/aoai-app-variation.py读取已生成图片并创建变体09-building-image-applications/python/aoai-solution.py结合元提示词的作业参考实现09-building-image-applications/typescript/image-generation-app/src/main.tsTypeScript 版实现使用AzureOpenAI客户端与client.images.generate默认部署名为gpt-image-109-building-image-applications/dotnet/notebook-azure-openai.dib.NET 交互式笔记本版本。下一步完成本课后可以继续学习第 10 课构建低代码 AI 应用见 10-building-low-code-ai-applications/README.md探索如何以更少的代码把 AI 能力接入业务应用。声明本文档由课程仓库内容整理编写原始文档为 AI 翻译的希伯来语版本translations/he/09-building-image-applications/README.md技术细节以仓库英文原版 09-building-image-applications/README.md 及对应源码为准。【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价