资讯动态

用 Nano Banana 复活图像档案:Google Cloud generative-ai 仓库的一致图像生成实战指南

发布时间:2026/9/14 3:03:36 来源:尧图企业网站定制
用 Nano Banana 复活图像档案Google Cloud generative-ai 仓库的一致图像生成实战指南【免费下载链接】generative-aiSample code and notebooks for Generative AI on Google Cloud, with Gemini Enterprise Agent Platform项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai导读本文基于 Google Cloud generative-ai 仓库 的媒体生成Media Generation模块围绕 一致图像生成实战 Notebook 展开讲解如何用 Nano Banana 图像模型gemini-3.1-flash-lite-image即 Nano Banana 2 Lite从一张老档案图中提取角色、制作角色参考图并仅凭提示词生成一系列风格与角色完全一致的场景图最终用networkx把整个生成过程可视化为一颗有向图。读完本文你将掌握Nano Banana 的 API 接入与生成参数配置、基于参考图 提示词的一致图像生成提示工程技巧、以及一套可复用的资产流水线提取→参考图→连续场景→元数据存档的完整实现思路。挑战让沉睡的图像档案重获新生几乎每个人手里都有一批旧图也许是几年前 AI 生成的一次性作品也许是随手拍下却再没使用的素材。传统做法是拿修图软件去改这需要非常专业的技术很多时候甚至不可能完成于是这些档案就永远躺在文件夹里吃灰。Notebook 用一句话点出核心痛点我们有很多值得在不同场景中复用的既有图像但修改图像是一道极其复杂、甚至不可能完成的任务。而状态越来越强的视觉模型让这个问题有了新的解法。作者设定的挑战分为三步从一张档案图出发——选定一张想复用的旧图提取角色生成全新的参考图——把图中角色挖出来做成设计参考仅用提示词 新资产生成一组连续图像——讲述这个角色的旅程故事。整个过程全部基于 Nano Banana 的图像生成与空间理解能力不需要任何传统图像编辑软件。环境搭建与 Gemini API 配置依赖安装Notebook 使用如下 Python 包见 一致图像生成实战 Notebook 的 Setup 一节google-genaiGoogle Gen AI Python SDK几行代码即可调用 Gemininetworkx图结构管理用于把生成过程建模为有向图tenacity请求重试管理google-genai的依赖matplotlib与pillow数据可视化与图像处理networkx的依赖。安装命令%pip install --quiet google-genai2.12.1 networkx[default]两种 API 接入方式调用 Gemini 图像模型有两种方式Gen AI SDK 提供统一接口只需通过环境变量区分方式一Agent Platform原 Vertex AI前提一个 Google Cloud 项目且已启用 Agent Platform API环境变量GOOGLE_GENAI_USE_ENTERPRISETrueGOOGLE_CLOUD_PROJECTPROJECT_IDGOOGLE_CLOUD_LOCATIONLOCATION 预览模型preview的 location 必须设为global正式可用GA模型则可就近选择区域。方式二Google AI StudioGemini API Key前提一个 Gemini API key环境变量GOOGLE_GENAI_USE_ENTERPRISEFalseGOOGLE_API_KEYAPI_KEY环境配置建议存放在源码之外IDE 中用.env文件Colab 中用左侧面板的 SecretsColab Enterprise 与 Workbench 则自动注入项目和区域。环境自动探测函数Notebook 提供了一套check_environment()辅助函数按手动配置 → 企业环境Workbench/Colab Enterprise→ Colab → 本地的优先级自动探测并设置环境变量核心逻辑如下def get_vars(getenv): # 限制 getenv 调用次数可能触发 Secret 访问的 UI 确认 if enterprise_str : getenv(GOOGLE_GENAI_USE_ENTERPRISE, ): enterprise enterprise_str.lower() in [true, 1] else: enterprise bool(getenv(GOOGLE_CLOUD_PROJECT, )) project getenv(GOOGLE_CLOUD_PROJECT, ) if enterprise else location getenv(GOOGLE_CLOUD_LOCATION, ) if project else api_key getenv(GOOGLE_API_KEY, ) if not project else return enterprise, project, location, api_key def check_define_env_vars(enterprise, project, location, api_key): match (enterprise, bool(project), bool(location), bool(api_key)): case (True, True, _, _): location location or global # Agent Platform - 项目 [区域] define_env_vars(enterprise, project, location, ) case (True, False, _, True): define_env_vars(enterprise, , , api_key) # Agent Platform - API key case (False, _, _, True): define_env_vars(enterprise, , , api_key) # Google AI Studio - API key case _: return False return True配置完成后通过check_configuration(client)打印当前使用的服务Agent Platform 或 Google AI Studio、项目前缀或 API key 掩码便于排查问题。模型选择Nano Banana 家族与 gemini-3.1-flash-lite-image本挑战选用的模型是Gemini 3.1 Flash-Lite ImageNano Banana 2 LiteNotebook 称其为 Nano Banana 家族中速度最快、成本最低的成员模型 ID 为NANO_BANANA_MODEL gemini-3.1-flash-lite-image关于该模型的能力边界仓库中的 Gemini 3.1 Flash Lite Image 入门教程 提供了可交叉验证的细节生成的图像均为1K分辨率并包含 C2PA 内容凭证元数据与 SynthID 水印一次请求最多可携带 14 张参考图但参考图数量限制在 3 张以内时一致性最佳支持从视频生成图像模型观察视频帧并基于视觉内容生成新图。而在本挑战中Notebook Gemini model 一节还给出了分辨率规则Nano Banana 2 Lite 生成 1K 图像1:1时为1024 × 1024像素其他宽高比按 token 等价的等效分辨率输出更大的 Nano Banana 模型可生成 2K 或 4K 图像。生成配置与请求助手函数生成参数配置Notebook 用GenerateContentConfigImageConfig统一封装请求参数RESPONSE_MODALITIES [IMAGE] # 可加 TEXT 以获得文本反馈或用于多轮对话 # 支持的宽高比1:1, 1:4, 4:1, 1:8, 8:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 ASPECT_RATIO 16:9 GENERATION_CONFIG GenerateContentConfig( response_modalitiesRESPONSE_MODALITIES, image_configImageConfig( aspect_ratioASPECT_RATIO, image_size1K, output_mime_typeimage/png if client.vertexai else None, ), )几个关键参数的实际影响aspect_ratio直接决定输出画幅。本挑战使用16:9生成1376 × 768像素的图像若省略该参数Gemini 会取输入图像多张时取最后一张的宽高比自动匹配最接近的受支持比例image_size设置为1KNano Banana 2 Lite 的最高档位output_mime_type仅在使用 Agent Platformclient.vertexai为真时指定image/png可确保输出格式稳定response_modalities声明响应包含图像模态加上TEXT后模型可以输出说明性文字便于迭代式对话。generate_content 与重试机制请求封装函数generate_content(sources, prompt)把若干 PIL 参考图与提示词拼进contents后调用client.models.generate_content随后从response.candidates[0].content.parts中逐 part 提取文本用 Markdown 显示与图像经part.as_image()._pil_image转成 PIL 图像def generate_content(sources, prompt): prompt prompt.strip() contents [*sources, prompt] if sources else prompt response None for attempt in get_retrier(): with attempt: response client.models.generate_content( modelNANO_BANANA_MODEL, contentscontents, configGENERATION_CONFIG, ) # ...从 response.candidates[0].content.parts 提取 image 并返回重试器基于tenacity最多尝试 7 次首次等待 10 秒、之后每次递增 1 秒仅在两类ClientError下重试def should_retry_request(err): if not isinstance(err, ClientError): return False match err.code: case 400 if err.message is not None and try again in err.message: # 项目首次访问 Cloud Storage服务代理预置时的瞬时错误 retry True case 429: # 临时项目配额只有 1 QPM 时的限流错误 retry True return retry这是生产级请求管理的关键一环图像生成请求耗时长、偶发限流加上重试能显著提升 Notebook 在 workshop 等受限环境下的稳定性。资产管理把生成过程变成可复用的资产流水线本挑战最有价值的设计之一是把生成结果抽象为资产Asset并记录每张图由谁生成。核心数据结构如下class AssetId(enum.StrEnum): ARCHIVE 0_archive # 原始档案图 ROBOT 1_robot # 角色卡正/背面 背包 MOUNTAINS 2_mountains # 第一场景山 VALLEY 3_valley # 山谷 FOREST 4_forest # 森林 CLEARING 5_clearing # 林中空地 ASCENSION 6_ascension # 攀山 SUMMIT 7_summit # 登顶 BRIDGE 8_bridge # 悬索桥 HAMMOCK 9_hammock # 吊床终点 dataclass class Asset: id: str source_ids: Sequence[str] # 生成该资产所依赖的源资产 ID祖先 prompt: str # 生成该资产所用的提示词 pil_image: PIL_Image class Assets(dict[str, Asset]): def set_asset(self, asset): # 新资产会覆盖同名旧资产 self[asset.id] asset def generate_image(source_ids, prompt, new_id): sources [assets[source_id].pil_image for source_id in source_ids] image generate_content(sources, prompt) if image and new_id: assets.set_asset(Asset(new_id, source_ids, prompt, image))注意Asset记录了两条关键元信息源资产 ID 列表血缘关系和生成提示词。这为后面的生成图可视化和PNG 元数据存档打下了基础——整个流水线不需要任何数据库靠数据结构本身就能完整回溯每一张图的来历。核心流程一从档案到角色参考图载入参考档案Notebook 从公共 URL 拉取一张 2024 年 7 月用 Imagen 3 beta 生成的羊毛毡小蓝机器人图作为档案素材提示词大意是白色背景上的一只小手感羊毛毡蓝色机器人玩具。当年这类一次性生成没有可复现性机器人似乎永远消失了——这正是档案复活的起点def load_archive(): image get_image_from_url(ARCHIVE_URL) # urllib 下载 PIL.Image.open assets.set_asset(Asset(AssetId.ARCHIVE, [], , image))简单提取的局限背景移除 ≠ 真正的提取第一版提示词试图把机器人抠出来Convert everything but the robot to pure white pixels.结果机器人被完美提取——但这本质上只是去背景很多模型已经能做到。作者特别强调了两点这类提示词沿用了图形软件的术语纯白像素而现在应该用图像构图的思维来思考使用传统二值掩码binary mask并不一定是好主意因为物体边缘和阴影承载着形状、纹理、位置、光照等重要信息粗暴抠图会把这些细节一起抹掉。角色卡Character Sheet基于空间理解的高级提取于是作者回到档案图直接让模型生成一张角色设定图character sheet一次完成多角度视图 新增道具- Scene: Character sheet of the robot, based on the provided image. - Setting: Isolated on a pure white background, razor-sharp focus, vibrant saturated colors, bright studio lighting. - Left Side: Straight-on front view of the robot wearing a small backpack made of warm chocolate-brown suede, with thin, matching straps around the shoulders. - Right Side: Straight-on back view of the robot wearing the same backpack. The backpacks flap is secured by a tiny, matte-brass, rounded-square ring buckle. The back of the robots head must be completely seamless. - Text: Small sans-serif text. Centered at the top, a caption ROBOT CHARACTER SHEET. At the bottom, label the left side FRONT VIEW and the right side BACK VIEW.Gemini 具备**空间理解spatial understanding**能力因此能在保持视觉特征的前提下提供不同视角。这次生成有几个值得注意的设计决策提示词聚焦于场景构图左正视图/右背视图、文字排版、光照这是媒体工作室常见的做法由于只描述了背包的部分特征比如一个搭扣未描述的部分每次生成会有差异——如果需要精确控制可以额外提供真实背包的参考照片并指示模型把背包改造成羊毛毡风格为了简洁背包直接画进了角色卡生产级管线通常会把它拆成单独的配件表accessory sheet反复生成会保持一致性保留原图中可见的机器人全部特征。至此角色卡资产1_robot成为后续所有场景的设计基准。核心流程二用参考图 提示词生成连续场景第一场景定基调第一张场景图决定了整个故事的整体观感值得多花时间打磨。作者用角色卡作为唯一参考生成了山景- Image 1: Reference robot character sheet. - Scene: Macro photography of a beautifully crafted miniature diorama. - Background: Soft focus on an infinite panoramic range of interspersed, dome-like smooth-felt mountains, in random shades of medium blue/green, all with curvy white snowcaps, extending over the entire horizon. - Foreground: On the bottom left, the robot stands on the edge of a medium-gray felt cliff, captured from a 3/4 rear view, looking out over a sea of clouds (made of white cotton). - Lighting: Studio, warm, clean and soft.作者刻意把山形容为dome-like圆顶状为后面角色站在山顶埋下伏笔。这里的经验是第一场景的提示词可以多迭代几次选最喜欢的变体因为它会以级联方式影响后续所有场景。连续转场山谷、森林与空地从第二张场景起生成输入通常包含两张参考图角色卡保角色一致 上一张场景保故事上下文。例如山谷场景- Image 1: Reference robot character sheet. - Image 2: Previous scene. - The robot has descended from the cliff into a gray felt valley. It stands in the center, seen directly from the back. It is holding/reading a felt map. - Large, smooth, round felt rocks in various beige/gray shades are visible on the sides. - Background: The distant infinite panoramic mountain range extending over the entire horizon. A thin layer of clouds obscures its base and the end of the valley. - Lighting: Golden hour light, soft and diffused.这里的提示词工程有三个要点显式引用输入图编号Image 1:…、Image 2:…至关重要——角色卡里有正/背两个机器人、上一场景里还有一个不指明编号the robot 可能指代任意一个。更保险的写法是the [entity] from image [number]没写的部分 创造空间山谷没有精确描述因此每次生成会有不同的、有趣的结果想要更高确定性就把提示词写精确光照是叙事工具山谷换成黄金时刻光线后整个场景氛围焕然一新。森林场景则展示了**控制跨场景残留物**的技巧- The robot continues its journey through the valley and faces a dense wall of giant, thin trees hiding the entire background. - The robot is on the right, seen from a 3/4 rear angle, looking up at the trees. It is no longer holding the map. Instead, its arms are raised beside its ears. - In the bottom-left and bottom-right corners, rocks (similar to Image 2) are partially visible.no longer holding the map 这句是故意的如果不说明模型会自行决定地图的去向拿着扔地上导致结果随机。而未描述的部分如视角、森林细节则会从上一次场景自然继承比如光源、质量和方向都会被保留。同理进入空地场景时只改了地面绿毡 白毡雪树木大多会被保留。登山、登顶、桥与吊床回到最初的山景用MOUNTAINS作参考而非 VALLEY直接回到该环境生成登山场景- Scene: A medium-wide shot of the robot climbing a broad, dome-shaped, medium-green mountain. - Composition: The mountain is centered, with the robot on the left slope shown from a 3/4 rear angle. - Action Details: The robot has both feet on the mountain and uses two miniature ice picks (felt, with brown handles and gray heads) to reach the summit, planting them into the bottom part of the white felt snowcap. - Background: The distant mountain range spans the entire horizon.登顶场景则是移除道具 姿态变化- The robot reaches the top and stands on the summit, seen from the front. - It is no longer holding the ice picks, which are planted upright in the snow on either side. - It has both arms raised as a sign of victory. Its face and hands are unchanged.随后进入大幅重组场景阶段——用祈使句imperative构图- Remove the ice picks. - Move the center mountain to the left edge of the image and add a slightly taller medium-blue mountain to the right edge. - Suspend a stylized felt bridge between the two mountains: its deck is made of stylized thick planks of plain felt in various wood shades. - Place the robot in the center of the bridge with one arm pointing toward the blue mountain. - Maintain the background. - View: Close-up.这条提示词展示了多个值得注意的现象新加的山既不同又一致桥以物理上可信的方式连接两座山巅而Remove the ice picks与前面的no longer holding the map同理——不给模型留出随机决策的空间。作者也坦诚指出局限性想生成角色从左向右走的侧面行走图很难把左右视图加进角色卡可以解决。最后是描述式descriptive提示词的示范——吊床场景- The robot is sleeping peacefully in a comfortable brown-and-tan tartan hammock that has replaced the bridge. - Both of the robots eyes are closed, in a sleeping state.桥→吊床的转变既保留了山巅的悬挂点又让从未出现过的闭眼侧卧姿态保持角色一致。至此作者用 9 张新的一致图像讲完了机器人从山到谷、穿林登山、最后安睡吊床的完整旅程。生成过程可视化networkx 有向图与 matplotlib 资产图所有新资产通过由…生成generated from关系相连从数据结构看就是一张有向图。用networkx构建def build_graph(assets): graph nx.DiGraph(assetsassets) for asset in assets.values(): graph.add_node(asset.id, assetasset) for asset in assets.values(): for source_id in asset.source_ids: graph.add_edge(source_id, asset.id) # 边 由 source 生成 return graph布局策略是把连接最多的节点放中间其余节点环绕排列def compute_node_positions(graph): center_node most_connected_node(graph) # max(graph.nodes, keygraph.degree) edge_nodes set(graph) - {center_node} pos nx.circular_layout(graph.subgraph(edge_nodes)) pos[center_node] np.array([0.0, 0.0]) return pos进阶的资产图则用matplotlib把每个节点渲染成真实的资产缩略图并做视觉分级绿色#34A853表示档案来源无提示词蓝色#4285F4表示新生成的资产有提示词边用点线样式绘制中心节点相关边为直边其余为rad0.15的曲线动画版GIF按生成顺序逐节点推进先展示该节点的提示词再替换为生成的图像GIF 用 MEDIANCUT 量化统一调色板首帧停留 3000ms、后续每帧 1000ms 循环播放。这套可视化既是对生成步骤的准确总结也天然是向团队/客户汇报生成管线的好素材。资产自足化把提示词与祖先关系写进 PNG 元数据你有没有生成过一张好图却忘了存下当时的精确上下文Notebook 的答案是把资产做成自足self-sufficient的——利用 PNG 的元数据块chunk直接保存source_ids和prompt无需数据库也不怕丢提示词def save_asset(asset, folder): image_path folder / f{asset.id}.png metadata PngInfo() metadata.add_text(source_ids, \n.join(asset.source_ids)) metadata.add_text(prompt, asset.prompt) asset.pil_image.save(image_path, pnginfometadata) def load_asset(image_path): asset_id image_path.stem with PIL.Image.open(image_path) as img: img.load() image_info img.info source_ids image_info.get(source_ids, ).split(\n) if image_info.get(source_ids) else [] prompt image_info.get(prompt, ) image img.copy() return Asset(asset_id, source_ids, prompt, image)配套的save_assets会把全部资产存入按时间戳命名的文件夹如2026-09-13_06-48-49/load_assets则遍历该文件夹重建完整的Assets之后可以立刻build_graph重新可视化。加载后即获得图像 提示词 血缘关系三位一体的资产为自动化管线铺平了道路。总结与自动化延伸Notebook 结尾总结了这次挑战的收获同时也是这套方法的核心价值主张一张图胜过千言万语从已有图像生成新图变得前所未有的容易纯靠构图创作/编辑图像人人都能当艺术指导描述式与祈使式提示词都有效前者适合自由发挥后者适合精确控制空间理解带来 3D 级操作多视角生成、姿态与道具的增删改输入输出都能包含文字角色卡里写文字、按FRONT/BACK VIEW标签理解输入一致性可以多层级保持角色、场景、纹理、光照、机位/镜头语言迭代速度大幅提升仍可迭代但获得超预期结果的感觉快了 10100 倍。从工程角度看这套流程本质上是一条生成管线可延伸的方向包括自动化改一个节点即可级联重新生成其后代节点并行变体同一组图像可以为不同美学风格、受众或模拟场景批量生成多个版本提示词工程化为清晰起见文中提示词保持简单生产环境可做成带标准化参数集的固定模板风格自由文中的场景设定是摄影棚拍摄实际上任何艺术风格写实、抽象、2D……都可行。延伸阅读Nano Banana Recipes 笔记本的 12 个实用配方同属本模块的 Nano Banana Recipes Notebook模块首页用另一组模型gemini-2.5-flash-image-previewGemini 2.5 Flash Image即第一代 Nano Banana整理了 12 个开箱即用的图像生成/编辑配方可作为一致图像生成的互补练习配方核心能力Recipe 1纯文本提示词从零生成图像Recipe 2用空白画布blank canvas控制宽高比Recipe 3图像外扩outpainting智能延伸画布边界Recipe 4指令式图像编辑加物件、换背景Recipe 5风格迁移如转换为梵高风格油画Recipe 6老照片修复与着色Recipe 7多张参考图融合成一个连贯场景Recipe 8虚拟试穿模特图 服装图Recipe 9产品场景重置电商/广告Recipe 10图像内嵌文字如菜单、海报Recipe 11角色一致性同角色多场景Recipe 12相机视角迁移如切换到俯拍机位该 Notebook 的核心配置同样值得对照学习MODEL_NAME gemini-2.5-flash-image-preview GENERATION_CONFIG types.GenerateContentConfig( temperature1, top_p0.95, max_output_tokens32768, response_modalities[TEXT, IMAGE], )其create_blank_canvas用 PIL 在内存中生成指定宽高比的空白画布作为Part传入请求1:1→1024×1024、16:9→1280×720、9:16→720×1280 等既控制输出画幅又给模型提供构图底版是本仓库中画布控制技巧的典型实现。如果你想深入 Nano Banana 2 Lite 的更多能力如视频生成图像、多参考图一致性边界、C2PA/SynthID 内容凭证可以继续阅读 Gemini 3.1 Flash Lite Image 入门教程。上述所有 Notebook 均可直接在 Colab、Colab Enterprise 或 Workbench 中运行只需按文中方式配置 Agent Platform 或 Google AI Studio 凭据即可。【免费下载链接】generative-aiSample code and notebooks for Generative AI on Google Cloud, with Gemini Enterprise Agent Platform项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

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

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

免费获取报价