Imagen を使用してコントロールに基づいて画像をカスタマイズする


このページでは、Imagenカスタマイズ機能を使用して、Firebase AI Logic SDK で指定された制御に基づいて画像を編集または生成する方法について説明します。

仕組み: テキスト プロンプトと、少なくとも 1 つのコントロール参照画像(描画や Canny エッジ画像など)を指定します。モデルはこれらの入力を使用して、制御画像に基づいて新しい画像を生成します。

たとえば、ロケットと月を描いた絵とテキスト プロンプトをモデルに提供して、その絵に基づいて水彩画を作成できます。

コードに移動

制御参照画像のタイプ

制御されたカスタマイズの参照画像は、フリーハンドCanny エッジ画像、または顔メッシュにできます。



始める前に

Vertex AI Gemini API を API プロバイダとして使用している場合にのみ使用できます。

まだ完了していない場合は、スタートガイドに沿って、記載されている手順(Firebase プロジェクトの設定、アプリと Firebase の連携、SDK の追加、選択した API プロバイダのバックエンド サービスの初期化、ImagenModel インスタンスの作成)を完了します。

この機能をサポートするモデル

Imagen は、capability モデルを通じて画像編集を提供します。

  • imagen-3.0-capability-001

Imagen モデルの場合、global のロケーションはサポートされていません。

制御されたカスタマイズ リクエストを送信する

次のサンプルは、提供された参照画像(この例では、ロケットや月などの宇宙の絵)に基づいて新しい画像を生成するようにモデルに要求する、制御されたカスタマイズ リクエストを示しています。参照画像は手書きのラフなスケッチまたはアウトラインであるため、コントロール タイプ CONTROL_TYPE_SCRIBBLE を使用します。

参照画像が Canny エッジ画像または顔メッシュの場合、次の変更を加えてこの例を使用することもできます。

このページの後半でプロンプト テンプレートを確認して、プロンプトの作成方法と、プロンプト内で参照画像を使用する方法について学習してください。

Swift

Imagen モデルを使用した画像編集は Swift ではサポートされていません。今年中にリリース予定です。

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 subject reference using the reference image.
    val controlReference = ImagenControlReference(
        image = referenceImage,
        referenceID = 1,
        controlType = CONTROL_TYPE_SCRIBBLE
    )

    // Provide a prompt that describes the final image.
    // The "[1]" links the prompt to the subject reference with ID 1.
    val prompt = "A cat flying through outer space arranged like the space scribble[1]"

    // Use the editImage API to perform the controlled customization.
    // Pass the list of references, the prompt, and an editing configuration.
    val editedImage = model.editImage(
        references = listOf(controlReference),
        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 subject reference using the reference image.
ImagenControlReference controlReference = new ImagenControlReference.Builder()
        .setImage(referenceImage)
        .setReferenceID(1)
        .setControlType(CONTROL_TYPE_SCRIBBLE)
        .build();

// Provide a prompt that describes the final image.
// The "[1]" links the prompt to the subject reference with ID 1.
String prompt = "A cat flying through outer space arranged like the space scribble[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 controlled customization.
// Pass the list of references, the prompt, and an editing configuration.
Futures.addCallback(model.editImage(Collections.singletonList(controlReference), 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

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 control reference using the reference image.
final controlReference = ImagenControlReference(
  image: referenceImage,
  referenceId: 1,
    controlType: ImagenControlType.scribble,
);

// Provide a prompt that describes the final image.
// The "[1]" links the prompt to the subject reference with ID 1.
final prompt = "A cat flying through outer space arranged like the space scribble[1]";

try {
  // Use the editImage API to perform the controlled customization.
  // Pass the list of references, the prompt, and an editing configuration.
  final response = await model.editImage(
    [controlReference],
    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

Imagen モデルを使用した画像編集は Unity ではサポートされていません。今年中にリリース予定です。

プロンプト テンプレート

リクエストでは、画像参照 ID を指定する ImagenControlReference を定義して、参照画像(最大 4 枚)を指定します。複数の画像に同じ参照 ID を設定できます(たとえば、同じアイデアの複数のメモなど)。

プロンプトを作成するときに、これらの ID を参照します。たとえば、プロンプトで [1] を使用して、参照 ID 1 の画像を参照します。

次の表に、コントロールに基づくカスタマイズのプロンプトを作成する際の出発点となるプロンプト テンプレートを示します。

ユースケース 参照画像 プロンプト テンプレート
制御されたカスタマイズ フリーハンド マップ(1) scribble map [1] に沿って画像を生成してください。説明は次のとおりです。「${STYLE_PROMPT} ${PROMPT}」 scribble map [1] に沿って画像を生成してください。説明は次のとおりです。「画像は、ゆったりとした筆遣いの印象派の油絵のスタイルにする必要があります。」自然光が差し込む雰囲気で、筆の跡が目立ちます。車の側面図。車は濡れて反射する路面に駐車しており、水たまりに街の光が反射している。
制御されたカスタマイズ Canny 制御画像(1) edge map [1] に沿って画像を生成してください。説明は次のとおりです。「${STYLE_PROMPT} ${PROMPT}」${STYLE_PROMPT} ${PROMPT} edge map [1] に沿って画像を生成してください。説明は次のとおりです。「この画像は、印象派の油絵風で、ゆったりとした筆遣いである必要があります。」自然光が差し込む雰囲気で、筆の跡が目立ちます。車の側面図。車は濡れて反射する路面に駐車しており、水たまりに街の光が反射している。
FaceMesh 入力を使用した人物画像のスタイル設定 サブジェクト画像(1 ~ 3)

フェイス メッシュ制御画像(1)
SUBJECT_DESCRIPTION [1] に関する画像を CONTROL_IMAGE [2] のポーズで作成してください。説明は次のとおりです。「SUBJECT_DESCRIPTION [1] のポートレート ${PROMPT} control image [2] のポーズで a woman with short hair [1] に関する画像を作成してください。説明は次のとおりです。「背景がぼかされた 3D アニメ スタイルの a woman with short hair [1] のポートレート。」笑顔でカメラを見ている、パステルカラーのキュートで愛らしいキャラクター ...
FaceMesh 入力を使用した人物画像のスタイル設定 サブジェクト画像(1 ~ 3)

フェイス メッシュ制御画像(1)
CONTROL_IMAGE [2] のポーズで SUBJECT_DESCRIPTION [1] に関する ${STYLE_PROMPT} 画像を作成してください。説明は次のとおりです。SUBJECT_DESCRIPTION [1] の肖像画 ${PROMPT} control image [2] のポーズで a woman with short hair [1] を描いた 3D アニメ風の画像を作成してください。説明は次のとおりです。「背景がぼかされた 3D アニメ風の a woman with short hair [1] のポートレート。笑顔でカメラを見ている、パステルカラーのトーンの、かわいらしくて愛らしいキャラクター ...



ベスト プラクティスと制限事項

ユースケース

カスタマイズ機能では、フリー スタイル プロンプトを使用できます。これにより、モデルがトレーニングされた以上のことができるという印象を与える可能性があります。次のセクションでは、カスタマイズの意図されたユースケースと、意図しないユースケースの例について説明します。

この機能は、意図されたユースケースで使用することをおすすめします。これらのユースケースでモデルをトレーニングしており、優れた結果が期待できるためです。逆に、モデルを本来のユースケース以外のことに使用すると、結果が不十分になる可能性があります。

想定されるユースケース

コントロールに基づくカスタマイズのユースケースは次のとおりです。

  • プロンプトと Canny エッジ制御画像に従った画像を生成します。

  • プロンプトと落書き画像に沿った画像を生成します。

  • 顔の表情を維持しながら、人物の写真をスタイル化します。

意図しないユースケースの例

以下は、コントロールに基づくカスタマイズの意図しないユースケースの一部です。このモデルはこれらのユースケース用にトレーニングされていないため、結果が不適切になる可能性があります。

  • プロンプトで指定されたスタイルを使用して画像を生成します。

  • 参照画像で提供される特定のスタイルに従ったテキストから画像を生成します。コントロール画像を使用して、画像構成をある程度制御できます。

  • 参照画像で指定された特定のスタイルに従ってテキストから画像を生成します。コントロール スクリブルを使用して、画像構成をある程度制御できます。

  • 参照画像で指定された特定のスタイルに従ったテキストから画像を生成します。コントロール画像を使用して、画像構成をある程度制御できます。画像に写っている人物が特定の表情をしている。

  • 2 人以上の人物が写っている写真をスタイル化し、表情を保持します。

  • ペットの写真を様式化して、絵に変換します。画像の構成(水彩など)を保持または指定します。