Imagen を使用して指定したスタイルに基づいて画像をカスタマイズする


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

仕組み: テキスト プロンプトと、特定のスタイル(パターン、テクスチャ、デザイン スタイルなど)を示す参照画像を 1 つ以上指定します。モデルはこれらの入力を使用して、参照画像の指定されたスタイルに基づいて新しい画像を生成します。

たとえば、提供した人気のある小売カタログの画像に基づいて、キッチンの新しい画像を生成できます。

コードに移動



始める前に

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

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

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

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

  • imagen-3.0-capability-001

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

スタイル カスタマイズ リクエストを送信する

次のサンプルは、提供された参照画像(この例では、ゴッホの「星月夜」)のスタイルで新しい画像を生成するようにモデルにリクエストするスタイル カスタマイズ リクエストを示しています。

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

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 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

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

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

プロンプト テンプレート

リクエストでは、ImagenStyleReference を定義して参照画像(最大 4 枚)を指定します。ImagenStyleReference では、画像の参照 ID(必要に応じてスタイルの説明も)を指定します。複数の画像に同じ参照 ID を設定できます(同じパターンの複数の写真など)。

プロンプトを作成するときに、これらの ID を参照します。たとえば、プロンプトで [1] を使用して、参照 ID 1 の画像を参照します。件名に説明を指定する場合は、プロンプトに含めることもできます。そうすることで、プロンプトを人間が読みやすくなります。

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

ユースケース 参照画像 プロンプト テンプレート
オブジェクト スタイル サブジェクト画像(1~4) 次のキャプション IMAGE_DESCRIPTION に基づいて、STYLE_DESCRIPTION [1] で画像を生成します。 次のキャプション a sign saying have a great day に基づいて、neon sign style [1] で画像を生成します。
フェイス メッシュ入力なしの人物画像のスタイル設定 サブジェクト画像(1~4) SUBJECT_DESCRIPTION [1] に関する画像を作成してください。説明は次のとおりです。「SUBJECT_DESCRIPTION [1] のポートレート」${PROMPT} a woman with short hair[1] に関する画像を作成してください。説明は次のとおりです。「背景がぼかされた 3D アニメ スタイルの a woman with short hair[1] のポートレート。」笑顔でカメラを見ている、パステルカラーのトーンの、かわいらしくて愛らしいキャラクター ...
人物の画像スタイル(フェイス メッシュ入力あり) サブジェクト画像(1~3)

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



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

ユースケース

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

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

想定されるユースケース

スタイルに基づくカスタマイズの

  • 参照画像で指定された特定のスタイルに沿って、テキスト入力から画像を生成します。

  • 人物の写真を変更する。

  • 人物の写真を変更し、表情を保持します。

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

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

  • テキストと参照画像を使用して画像を生成し、参照画像から生成された構図をある程度制御できるようにします。

  • 特定の表情をした人物が写っている参照画像から、その人物の画像を生成します。

  • 2 人を別のシーンに配置し、その人物のアイデンティティを保持しながら、参照画像を使用して出力画像のスタイル(油絵など)を指定します。

  • ペットの写真をスタイライズして絵に変換し、画像の構図を保持または指定します。

  • クッキーやソファなどの商品を、さまざまな角度で、特定の画像スタイル(特定の色のフォトリアリスティック、照明スタイル、アニメーションなど)に従って、さまざまなシーンに配置します。