使用 Imagen 根据指定样式自定义图片


本页介绍了如何使用 Imagen自定义功能,通过 Firebase AI Logic SDK 根据指定的风格修改或生成图片。

运作方式:您提供一个文本提示和至少一张显示特定样式(例如图案、纹理或设计风格)的参考图片。模型会使用这些输入内容,根据参考图片中指定的风格生成新图片。

例如,您可以根据您提供的热门零售目录中的图片生成新的厨房图片。

跳转到代码



准备工作

仅在将 Vertex AI Gemini API 用作 API 提供方时可用。

如果您尚未完成入门指南,请先完成该指南。该指南介绍了如何设置 Firebase 项目、将应用连接到 Firebase、添加 SDK、为所选的 API 提供程序初始化后端服务,以及创建 ImagenModel 实例。

支持此功能的模型

Imagen 通过其 capability 模型提供图片编辑功能:

  • imagen-3.0-capability-001

请注意,对于 Imagen 模型,global 位置受支持。

发送样式自定义请求

以下示例展示了一个风格自定义请求,该请求要求模型生成一张具有所提供参考图片风格的新图片(在本示例中,参考图片为梵高的《星夜》)。

请在本页后面部分查看提示模板,了解如何撰写提示以及如何在提示中使用参考图片。

Swift

Swift 不支持使用 Imagen 模型进行图片编辑。今年晚些时候再回来查看!

Kotlin

// Using this SDK to access Imagen models is a Preview release and requires opt-in
@OptIn(PublicPreviewAPI::class)
suspend fun customizeImage() {
    // Initialize the Vertex AI Gemini API backend service
    // Optionally specify the location to access the model (for example, `us-central1`)
    val ai = Firebase.ai(backend = GenerativeBackend.vertexAI(location = "us-central1"))

    // Create an `ImagenModel` instance with an Imagen "capability" model
    val model = ai.imagenModel("imagen-3.0-capability-001")

    // This example assumes 'referenceImage' is a pre-loaded Bitmap.
    // In a real app, this might come from the user's device or a URL.
    val referenceImage: Bitmap = TODO("Load your reference image Bitmap here")

    // Define the style reference using the reference image.
    val styleReference = ImagenStyleReference(
        image = referenceImage,
        referenceID = 1,
        description = "Van Gogh style"
    )

    // Provide a prompt that describes the final image.
    // The "[1]" links the prompt to the style reference with ID 1.
    val prompt = "A cat flying through outer space, in the Van Gogh style[1]"

    // Use the editImage API to perform the style customization.
    // Pass the list of references, the prompt, and an editing configuration.
    val editedImage = model.editImage(
        references = listOf(styleReference),
        prompt = prompt,
        config = ImagenEditingConfig(
            editSteps = 50 // Number of editing steps, a higher value can improve quality
        )
    )

    // Process the result
}

Java

// Initialize the Vertex AI Gemini API backend service
// Optionally specify the location to access the model (for example, `us-central1`)
// Create an `ImagenModel` instance with an Imagen "capability" model
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.vertexAI("us-central1"))
        .imagenModel(
                /* modelName */ "imagen-3.0-capability-001");

ImagenModelFutures model = ImagenModelFutures.from(imagenModel);

// This example assumes 'referenceImage' is a pre-loaded Bitmap.
// In a real app, this might come from the user's device or a URL.
Bitmap referenceImage = null; // TODO("Load your image Bitmap here");

// Define the style reference using the reference image.
ImagenStyleReference subjectReference = new ImagenStyleReference.Builder()
        .setImage(referenceImage)
        .setReferenceID(1)
        .setDescription("Van Gogh style")
        .build();

// Provide a prompt that describes the final image.
// The "[1]" links the prompt to the style reference with ID 1.
String prompt = "A cat flying through outer space, in the Van Gogh style[1]";

// Define the editing configuration.
ImagenEditingConfig imagenEditingConfig = new ImagenEditingConfig.Builder()
        .setEditSteps(50) // Number of editing steps, a higher value can improve quality
        .build();

// Use the editImage API to perform the style customization.
// Pass the list of references, the prompt, and the editing configuration.
Futures.addCallback(model.editImage(Collections.singletonList(styleReference), prompt, imagenEditingConfig), new FutureCallback<ImagenGenerationResponse>() {
    @Override
    public void onSuccess(ImagenGenerationResponse result) {
        if (result.getImages().isEmpty()) {
            Log.d("TAG", "No images generated");
        }
        Bitmap bitmap = result.getImages().get(0).asBitmap();
        // Use the bitmap to display the image in your UI
    }

    @Override
    public void onFailure(Throwable t) {
        // ...
    }
}, Executors.newSingleThreadExecutor());

Web

Web 应用不支持使用 Imagen 模型进行图片编辑。今年晚些时候再回来查看!

Dart

import 'dart:typed_data';
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Vertex AI Gemini API backend service
// Optionally specify a location to access the model (for example, `us-central1`)
final ai = FirebaseAI.vertexAI(location: 'us-central1');

// Create an `ImagenModel` instance with an Imagen "capability" model
final model = ai.imagenModel(model: 'imagen-3.0-capability-001');

// This example assumes 'referenceImage' is a pre-loaded Uint8List.
// In a real app, this might come from the user's device or a URL.
final Uint8List referenceImage = Uint8List(0); // TODO: Load your reference image data here

// Define the style reference using the reference image.
final styleReference = ImagenStyleReference(
  image: referenceImage,
  referenceId: 1,
  description: 'Van Gogh style',
);

// Provide a prompt that describes the final image.
// The "[1]" links the prompt to the style reference with ID 1.
final prompt = "A cat flying through outer space, in the Van Gogh style[1]";

try {
  // Use the editImage API to perform the style customization.
  // Pass the list of references, the prompt, and an editing configuration.
  final response = await model.editImage(
    [styleReference],
    prompt,
    config: ImagenEditingConfig(
      editSteps: 50, // Number of editing steps, a higher value can improve quality
    ),
  );

  // Process the result.
  if (response.images.isNotEmpty) {
    final editedImage = response.images.first.bytes;
    // Use the editedImage (a Uint8List) to display the image, save it, etc.
    print('Image successfully generated!');
  } else {
    // Handle the case where no images were generated.
    print('Error: No images were generated.');
  }
} catch (e) {
  // Handle any potential errors during the API call.
  print('An error occurred: $e');
}

Unity

Unity 不支持使用 Imagen 模型进行图片编辑。今年晚些时候再回来查看!

提示模板

在请求中,您可以通过定义 ImagenStyleReference 来提供参考图片(最多 4 张),并在其中指定图片的参考 ID(还可以选择指定样式说明)。请注意,多张图片可以具有相同的参考 ID(例如,同一图案的多张照片)。

然后,在编写提示时,您会引用这些 ID。例如,您可以在提示中使用 [1] 来引用参考 ID 为 1 的图片。如果您提供主题说明,也可以将其纳入提示中,以便人类更轻松地阅读提示。

下表提供了提示模板,您可以从这些模板入手,撰写基于风格的自定义提示。

使用场景 参考图片 提示模板 示例
对象风格 主题图片 (1-4) Generate an image in STYLE_DESCRIPTION [1] based on the following caption: IMAGE_DESCRIPTION. Generate an image in neon sign style [1] based on the following caption: a sign saying have a great day.
不使用人脸网格输入的人物图片风格化处理 主题图片 (1-4) Create an image about SUBJECT_DESCRIPTION [1] to match the description: a portrait of SUBJECT_DESCRIPTION [1] ${PROMPT} Create an image about a woman with short hair[1] to match the description: a portrait of a woman with short hair[1] in 3d-cartoon style with blurred background. A cute and lovely character, with a smiling face, looking at the camera, pastel color tone ...
使用人脸网格输入的人物图片风格化处理 主题图片 (1-3)

Facemesh 控制图片 (1)
Create an image about SUBJECT_DESCRIPTION [1] in the pose of the CONTROL_IMAGE [2] to match the description: a portrait of SUBJECT_DESCRIPTION [1] ${PROMPT} Create an image about a woman with short hair [1] in the pose of the control image [2] to match the description: a portrait of a woman with short hair [1] in 3d-cartoon style with blurred background. A cute and lovely character, with a smiling face, looking at the camera, pastel color tone ...



最佳做法和限制

使用场景

自定义功能可提供自由式提示,这可能会给人一种印象,即模型能完成的任务比训练时学到的更多。以下部分介绍了自定义功能的预期应用场景,以及一些并非详尽无遗的非预期应用场景示例。

我们建议您将此功能用于预期应用场景,因为我们已针对这些应用场景训练了模型,可期望获得良好的结果。 反之,如果您让模型执行预期应用场景之外的任务,则应预期结果不理想。

预期应用场景

以下是基于风格的自定义功能的预期应用场景:

  • 根据文本输入生成图片,且该图片采用通过参考图片提供的特定风格。

  • 更改人物照片。

  • 更改人物照片并保留其面部表情。

非预期应用场景示例

下面列出了基于风格的自定义功能的非预期应用场景(并非详尽无遗)。该模型未针对这些使用场景进行训练,因此很可能会生成不理想的结果。

  • 根据文本和参考图片生成图片,目的是对通过参考图片生成的构图进行一定程度的控制。

  • 根据参考图片生成人物图片,且该参考图片中的人物具有特定的面部表情。

  • 将两个人放置到一个不同的场景中,在保留其身份特征的同时使用参考图片指定输出图片的风格(例如油画风格)。

  • 对宠物照片进行风格化处理并将其转换为绘画,同时保留或指定图片的构图。

  • 将饼干或沙发等产品以不同的产品角度置于不同的场景中,同时遵循特定的图片风格(例如具有特定颜色、采光风格或动画效果的写实图片)。