
使用 Azure OpenAI 构建图像生成应用从 DALL-E 原理到 gpt-image-1 实战【免费下载链接】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 课09-building-image-applications的技术指南围绕文本描述生成图像这一核心主题展开。你将掌握 DALL-E / Midjourney 等图像生成模型的工作原理学会使用 Azure OpenAI 的gpt-image-1模型从零搭建可运行的图像生成应用并通过温度参数与 metaprompt元提示精确控制生成结果最终为教育场景Edu4All 项目交付一套带内容边界的图像生成方案。为什么构建图像生成应用大语言模型LLM的能力远不止文本生成它同样可以从文本描述直接生成图像。将图像作为一种模态在众多行业都有极高的实用价值医疗科技MedTech、建筑设计、旅游、游戏开发等。图像生成应用是探索生成式 AI 能力的最佳切入点之一典型用途包括图像编辑与合成针对多种使用场景生成图像例如图像编辑、图像合成。跨行业落地为医疗科技、旅游、游戏开发等不同行业批量生成所需的视觉素材。本课程沿用了贯穿全书的虚构创业公司Edu4All学生需要为自己的评估项目创作图像——可能是为童话配插画、为故事创造新角色或是把抽象的想法和概念可视化。例如当课堂主题是世界地标时学生可以用类似Dog next to Eiffel Tower in early morning sunlight清晨阳光下埃菲尔铁塔旁的小狗这样的提示词生成配图。DALL-E 与 Midjourney两大主流图像生成模型DALL-EOpenAI与Midjourney是当下最流行的两个图像生成模型二者都允许用户通过自然语言 prompt提示词生成图像。DALL-EDALL-E 是一个从文本描述生成图像的生成式 AI 模型其本质是两个模型的组合CLIP 与扩散注意力diffused attentionCLIP负责从图像和文本中生成 embedding数据的数值化表示实现文本与图像在语义空间的对齐。扩散注意力负责从 embedding 生成图像。DALL-E 在海量的图像与文本数据集上训练因此能够根据文本描述生成图像例如戴帽子的猫或莫霍克发型的狗。MidjourneyMidjourney 的工作方式与 DALL-E 类似同样从文本 prompt 生成图像也支持诸如 a cat in a hat戴帽子的猫、a dog with a mohawk莫霍克发型的狗这类描述。两者主要差异在于产品形态、生成风格与使用方式但从 API 应用开发的角度看核心思路一致——用自然语言驱动图像生成。工作原理自回归 Transformer 的图像生成过程以 DALL-E 为例它基于 Transformer 架构核心是自回归 Transformerautoregressive transformer。其生成机制可以理解为模型根据文本描述逐像素pixel地生成图像每生成一个像素就把已生成的像素作为上下文用于预测下一个像素如此反复经过神经网络中的多个层直到整幅图像生成完毕。通过这一过程DALL-E 能够控制生成图像中的属性、对象、特征等要素。后续的 DALL-E 2、DALL-E 3 在生成图像的控制力上更进一步例如更精确地遵循 prompt 语义。需要特别说明在 Azure OpenAI 平台上gpt-image-1是当前的图像生成模型而 DALL-E 3 已进入 legacy 状态、不再支持新建部署新项目应直接选择gpt-image-1。构建第一个图像生成应用依赖库清单搭建图像生成应用只需要四个 Python 库库作用python-dotenv强烈推荐用于把密钥等敏感信息放在.env文件中与代码分离openai与 OpenAI / Azure OpenAI API 交互的官方 SDKpillow在 Python 中处理图像打开、显示、保存requests发起 HTTP 请求用于下载生成的图像文件第一步创建并部署 Azure OpenAI 模型如果还没有 Azure OpenAI 资源需要先在 Azure 门户Azure AI Foundry创建资源与模型部署模型选择gpt-image-1当前代次的 Azure OpenAI 图像模型DALL-E 3 为 legacy 模型不再提供新部署。创建完成后在 Foundry 门户的 Deployments部署区域可以找到对应的 endpoint 与 API Key。第二步配置 .env 与依赖创建.env文件写入以下三项配置AZURE_OPENAI_ENDPOINTyour endpoint AZURE_OPENAI_API_KEYyour key AZURE_OPENAI_DEPLOYMENTgpt-image-1将依赖收集到requirements.txt与仓库 09-building-image-applications/requirements.txt 保持一致python-dotenv openai pillow requests第三步创建虚拟环境并安装依赖Linux / macOSpython3 -m venv venv source venv/bin/activate pip install -r requirements.txtWindowspython3 -m venv venv venv\Scripts\activate.bat第四步编写 app.py以下代码与仓库实现 09-building-image-applications/python/aoai-app.py 同源是完整的可运行版本from openai import AzureOpenAI, BadRequestError import os import requests from PIL import Image import dotenv import json # 从 .env 加载环境变量 dotenv.load_dotenv() # 配置 Azure OpenAI 服务客户端 client AzureOpenAI( api_keyos.environ[AZURE_OPENAI_API_KEY], # 默认项可省略 api_version 2024-10-21, # 依据模型要求选择 API 版本 azure_endpointos.environ[AZURE_OPENAI_ENDPOINT] ) model os.environ[AZURE_OPENAI_DEPLOYMENT] try: # 调用图像生成 API result client.images.generate( modelmodel, promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1 ) generation_response json.loads(result.model_dump_json()) # 设置图像存储目录 image_dir os.path.join(os.curdir, images) if not os.path.isdir(image_dir): os.mkdir(image_dir) # 初始化图像路径注意文件类型应为 png image_path os.path.join(image_dir, generated-image.png) # 提取响应中的图像 URL 并下载 image_url generation_response[data][0][url] generated_image requests.get(image_url).content with open(image_path, wb) as image_file: image_file.write(generated_image) # 用系统默认图像查看器打开图片 image Image.open(image_path) image.show() # 捕获异常 except BadRequestError as err: print(err) finally: print(completed!)代码逐段拆解导入依赖引入openaiSDK、os环境变量、requestsHTTP 下载、PIL图像处理、dotenv密钥管理。加载环境变量dotenv.load_dotenv()读取.env文件中的AZURE_OPENAI_ENDPOINT、AZURE_OPENAI_API_KEY、AZURE_OPENAI_DEPLOYMENT保证密钥不写死在代码里。配置客户端用AzureOpenAI(...)构造客户端。仓库源码在注释中提醒API 版本需要对照 Microsoft Foundry 文档中该模型所要求的版本本仓库统一使用2024-10-21。生成图像client.images.generate(...)发起生成请求返回一个包含图像 URL 的 JSON 对象随后用requests.get(image_url).content下载二进制内容并写入本地 PNG 文件。展示图像Image.open(image_path)与image.show()调用系统默认查看器打开图片。异常处理捕获BadRequestError打印错误信息finally中打印完成标记保证流程可观测。生成参数详解result client.images.generate( modelmodel, promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n1 )prompt用于生成图像的文本提示词。本例为 Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils马背上的兔子举着棒棒糖身处长满水仙花的薄雾草地。size生成图像的尺寸。本例为 1024x1024 像素可按需选用 1024x1792、1792x1024 等其他规格。n一次生成的图像数量。课程文档示例为 1 张意大利语翻译版中的说明为 2 张实际以你调用时的需求为准。model指定部署的模型即.env中的AZURE_OPENAI_DEPLOYMENT。temperature控制生成随机性的参数取值范围 010 表示输出确定性高1 表示输出随机性强默认值为 0.7详见下文温度一节。图像生成的进阶能力除了从零生成图像还可以对图像做更多操作。图像编辑Edit通过提供已有图像 蒙版mask 提示词可以局部修改图像。例如为兔子加上一顶帽子提供原图、标明待修改区域的蒙版以及描述要做什么的文本 prompt。注意这一能力在 DALL-E 3 上不受支持需使用 gpt-image-1。示例使用 GPT Imageresponse 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课程 notebook09-building-image-applications/python/aoai-assignment.ipynb中的示例则用client.images.edit配合n1、size1024x1024参数将戴帽子的兔子叠加到基础图像上。仓库images目录下的 sunlit_lounge.png、mask.png 与 sunlit_lounge_result.png 三张图展示了编辑前后的对照基础图只有带泳池的客厅最终图则加入了火烈鸟。创建变体Variation变体的思路是取一张已有图像要求模型生成它的多个变体。只需提供图像与文本 prompt 即可response client.images.create_variation( imageopen(bunny-lollipop.png, rb), n1, size1024x1024 ) image_url response.data[0].url注意create_variation仅在 OpenAI 平台的 DALL-E 2 模型上受支持gpt-image-1不支持。仓库提供了两个可运行的变体示例09-building-image-applications/python/aoai-app-variation.pyAzure OpenAI 版读取先前生成的images/generated-image.png并输出generated_variation.png与 09-building-image-applications/python/oai-app-variation.pyOpenAI 版捕获BadRequestError。其中 aoai-app-variation.py 展示了完整的调用链打开已有图像 →client.images.create_variation(imageopen(image_path, rb), n1, size1024x1024)→ 解析响应 URL → 下载并展示变体。温度控制生成的随机性温度temperature是生成式 AI 模型中控制输出随机性的参数取值 010输出趋于确定性同样的 prompt 得到高度相似的结果1输出趋于随机同样的 prompt 每次结果差异明显默认值0.7。对同一 prompt 运行两次观察温度的影响。课程使用固定 promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils在默认温度下连续生成两张图可以看到画面相似但不完全相同——第一次生成结果见 v1-generated-image.png第二次见 v2-generated-image.png。接下来把温度设为 0让输出更确定generation_response client.images.generate( promptBunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils, size1024x1024, n2, temperature0 )将temperature0与默认温度的结果对比仓库中温度 0 的两张输出见 v1-temp-generated-image.png 与 v2-temp-generated-image.png可以明显看出温度越低多次生成结果越相似。实战建议需要风格统一的批量出图如教材配图、电商素材时用低温度需要发散创意、探索多种构图时用较高温度。用 Metaprompt 为应用划定内容边界演示应用已经能为客户生成图像但生产环境必须设置内容边界——例如不能生成不适合工作场合、不适合儿童观看的图像。这可以通过metaprompt元提示实现。Metaprompt 的工作原理Metaprompt 是一段用于控制生成式 AI 模型输出的文本提示它被放置在实际文本 prompt之前与用户输入一起封装进同一个 prompt 中。应用通过 metaprompt 约束模型输出保证生成结果符合预期标准。一个典型的 metaprompt 模板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)在应用中使用 metapromptdisallow_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要点拆解disallow_list以字符串形式枚举禁用主题武器、暴力、血腥、裸露、成人内容等便于集中维护meta_prompt用 f-string 将约束规则与disallow_list组合成统一的系统约束段最终prompt由meta_prompt 用户请求拼接而成模型在生成图像时会同时考虑这两部分约束。从仓库实现 09-building-image-applications/python/aoai-solution.py 可以看到该模式完整落地在课程作业的参考答案中。课程作业为 Edu4All 学生赋能回到 Edu4All 场景现在需要让学生能够为自己的评估项目生成包含地标monuments的图像。地标选择由学生自行决定鼓励发挥创造力把地标放置在不同的情境中。参考答案仓库 09-building-image-applications/python/aoai-solution.py 给出了一份完整实现核心逻辑如下此处略去与上文重复的客户端初始化、下载与展示代码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: result client.images.generate( modelmodel, promptprompt, size1024x1024, n1 ) # ... 下载与展示逻辑同上 except BadRequestError as err: print(err)该方案演示了三个关键点用 metaprompt 保证生成内容面向儿童且安全合规用详细的地点/时间/人物描述提升生成质量用try/except保证错误可观测。仓库配套资源导览本课除课程文档外仓库还提供多种可直接运行与对比学习的资源09-building-image-applications/python/aoai-app.pyAzure OpenAI 版完整应用含json.loads(result.model_dump_json())响应解析与finally完成标记09-building-image-applications/python/oai-app.pyOpenAI 平台版使用modeldall-e-3并示范了 API Key 缺失校验与requests.get(..., timeout30)下载加固09-building-image-applications/python/aoai-app-variation.py 与 09-building-image-applications/python/oai-app-variation.py图像变体生成09-building-image-applications/python/aoai-assignment.ipynb 与 09-building-image-applications/python/oai-assignment.ipynbJupyter Notebook 交互式作业含编辑示例与变体说明09-building-image-applications/requirements.txt依赖清单09-building-image-applications/typescript/image-generation-appTypeScript 版本示例便于对照不同语言的 SDK 用法。小结通过本课你可以完整掌握图像生成模型DALL-E / Midjourney的基本原理与差异基于 Azure OpenAIgpt-image-1从零构建可运行的图像生成应用环境配置 → 客户端初始化 → 生成 → 下载 → 展示通过 temperature 控制生成随机性通过 metaprompt 为应用设定内容边界保障生成结果适合目标受众如儿童教育场景。下一课将进入 10-building-low-code-ai-applications学习如何使用低代码方式构建 AI 应用。【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考