Imagen을 사용하여 이미지 배경 바꾸기


이 페이지에서는 Firebase AI Logic SDK를 사용하여 Imagen이미지의 배경을 바꾸는 방법을 설명합니다.

배경 바꾸기는 마스크 기반 수정 (구체적으로 인페인팅)의 한 유형입니다. 마스크는 수정할 특정 영역을 정의하는 디지털 오버레이입니다.

작동 방식: 원본 이미지와 배경에 마스크를 정의하는 해당 마스크 이미지를 제공합니다. 자동 배경 감지를 사용하거나 배경 마스크를 직접 제공합니다. 변경하려는 내용을 설명하는 텍스트 프롬프트도 제공합니다. 그러면 모델이 새 배경을 생성하고 적용합니다.

예를 들어 전경 (예: 제품 이미지)에 영향을 주지 않고 피사체 또는 객체 주변의 설정을 변경할 수 있습니다.

자동 감지된 배경의 코드로 이동 배경 마스크 제공 코드로 이동

시작하기 전에

Vertex AI Gemini API을 API 제공자로 사용하는 경우에만 사용할 수 있습니다.

아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 API 제공업체의 백엔드 서비스를 초기화하고, ImagenModel 인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료합니다.

이 기능을 지원하는 모델

Imagencapability 모델을 통해 이미지 편집을 제공합니다.

  • imagen-3.0-capability-001

Imagen 모델의 경우 global 위치는 지원되지 않습니다.

자동 배경 감지를 사용하여 배경 바꾸기

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.

다음 샘플은 자동 배경 감지를 사용하여 이미지의 배경을 바꾸는 방법을 보여줍니다. 원본 이미지와 텍스트 프롬프트를 제공하면 Imagen가 배경의 마스크를 자동으로 감지하고 만들어 원본 이미지를 수정합니다.

Swift

Swift에서는 Imagen 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.

Kotlin

자동 배경 감지를 사용하여 배경을 바꾸려면 ImagenBackgroundMask를 지정합니다. editImage()를 사용하여 편집 구성이 ImagenEditMode.INPAINT_INSERTION를 사용하도록 설정합니다.

// 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 'originalImage' is a pre-loaded Bitmap.
    // In a real app, this might come from the user's device or a URL.
    val originalImage: Bitmap = TODO("Load your original image Bitmap here")

    // Provide the prompt describing the new background.
    val prompt = "space background"

    // Use the editImage API to replace the background.
    // Pass the original image, the prompt, and an editing configuration.
    val editedImage = model.editImage(
        sources = listOf(
            ImagenRawImage(originalImage),
            ImagenBackgroundMask(), // Use ImagenBackgroundMask() to auto-generate the mask.
        ),
        prompt = prompt,
        // Define the editing configuration for inpainting and background replacement.
        config = ImagenEditingConfig(ImagenEditMode.INPAINT_INSERTION)
    )

    // Process the resulting 'editedImage' Bitmap, for example, by displaying it in an ImageView.
}

Java

자동 배경 감지를 사용하여 배경을 바꾸려면 ImagenBackgroundMask를 지정합니다. editImage()를 사용하여 편집 구성이 ImagenEditMode.INPAINT_INSERTION를 사용하도록 설정합니다.

// 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 'originalImage' is a pre-loaded Bitmap.
// In a real app, this might come from the user's device or a URL.
Bitmap originalImage = null; // TODO("Load your image Bitmap here");

// Provide the prompt describing the new background.
String prompt = "space background";

// Define the list of sources for the editImage call.
// This includes the original image and the auto-generated mask.
ImagenRawImage rawOriginalImage = new ImagenRawImage(originalImage);
ImagenBackgroundMask rawMaskedImage = new ImagenBackgroundMask(); // Use ImagenBackgroundMask() to auto-generate the mask.

// Define the editing configuration for inpainting and insertion.
ImagenEditingConfig config = new ImagenEditingConfig.Builder()
        .setEditMode(ImagenEditMode.INPAINT_INSERTION)
        .build();

// Use the editImage API to replace the background.
// Pass the original image, the auto-generated masked image, the prompt, and an editing configuration.
Futures.addCallback(model.editImage(Arrays.asList(rawOriginalImage, rawMaskedImage), prompt, config), new FutureCallback<ImagenGenerationResponse>() {
    @Override
    public void onSuccess(ImagenGenerationResponse result) {
        if (result.getImages().isEmpty()) {
            Log.d("ImageEditor", "No images generated");
        }
        Bitmap editedImage = result.getImages().get(0).asBitmap();
        // Process and use the bitmap to display the image in your UI
    }

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

Web

Imagen 모델을 사용한 이미지 편집은 웹 앱에서 지원되지 않습니다. 올해 다시 확인해 주세요.

Dart

자동 배경 감지를 사용하여 배경을 바꾸려면 ImagenBackgroundMask를 지정합니다. editImage()를 사용하여 편집 구성이 ImagenEditMode.inpaintInsertion를 사용하도록 설정합니다.

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 'originalImage' is a pre-loaded Uint8List.
// In a real app, this might come from the user's device or a URL.
final Uint8List originalImage = Uint8List(0); // TODO: Load your original image data here.

// Provide the prompt describing the new background.
final prompt = 'space background';

try {
  // Use the editImage API to replace the background.
  // Pass the original image, the prompt, and an editing configuration.
  final response = await model.editImage(
    sources: [
      ImagenRawImage(originalImage),
      ImagenBackgroundMask(), // Use ImagenBackgroundMask() to auto-generate the mask.
    ],
    prompt: prompt,
    // Define the editing configuration for inpainting and background replacement.
    config: const ImagenEditingConfig(
      editMode: ImagenEditMode.inpaintInsertion,
    ),
  );

  // 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 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.

제공된 마스크를 사용하여 배경 바꾸기

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.

다음 샘플은 제공한 이미지에 정의된 배경 마스크를 사용하여 이미지의 배경을 바꾸는 방법을 보여줍니다. 원본 이미지, 텍스트 프롬프트, 마스크 처리된 이미지를 제공합니다.

Swift

Swift에서는 Imagen 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.

Kotlin

제공된 마스크를 사용하여 배경을 바꾸려면 마스크 처리된 이미지와 함께 ImagenRawMask을 지정합니다. editImage()를 사용하여 편집 구성이 ImagenEditMode.INPAINT_INSERTION를 사용하도록 설정합니다.

// 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 'originalImage' is a pre-loaded Bitmap.
    // In a real app, this might come from the user's device or a URL.
    val originalImage: Bitmap = TODO("Load your original image Bitmap here")

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

    // Provide the prompt describing the new background.
    val prompt = "space background"

    // Use the editImage API to replace the background.
    // Pass the original image, the masked image, the prompt, and an editing configuration.
    val editedImage = model.editImage(
        referenceImages = listOf(
            ImagenRawImage(originalImage.toImagenInlineImage()),
            ImagenRawMask(maskImage.toImagenInlineImage()), // Use ImagenRawMask() to provide your own masked image.
        ),
        prompt = prompt,
        // Define the editing configuration for inpainting and background replacement.
        config = ImagenEditingConfig(ImagenEditMode.INPAINT_INSERTION)
    )

    // Process the resulting 'editedImage' Bitmap, for example, by displaying it in an ImageView.
}

Java

제공된 마스크를 사용하여 배경을 바꾸려면 마스크 처리된 이미지와 함께 ImagenRawMask을 지정합니다. editImage()를 사용하여 편집 구성이 ImagenEditMode.INPAINT_INSERTION를 사용하도록 설정합니다.

// 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 'originalImage' is a pre-loaded Bitmap.
// In a real app, this might come from the user's device or a URL.
Bitmap originalImage = null; // TODO("Load your original image Bitmap here");

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

// Provide the prompt describing the new background.
String prompt = "space background";

// Define the list of source images for the editImage call.
ImagenRawImage rawOriginalImage = new ImagenRawImage(originalImage);
ImagenBackgroundMask rawMaskedImage = new ImagenRawMask(maskImage); // Use ImagenRawMask() to provide your own masked image.

// Define the editing configuration for inpainting and background replacement.
ImagenEditingConfig config = new ImagenEditingConfig.Builder()
        .setEditMode(ImagenEditMode.INPAINT_INSERTION)
        .build();

// Use the editImage API to replace the background.
// Pass the original image, the masked image, the prompt, and an editing configuration.
Futures.addCallback(model.editImage(Arrays.asList(rawOriginalImage, rawMaskedImage), prompt, config), new FutureCallback<ImagenGenerationResponse>() {
    @Override
    public void onSuccess(ImagenGenerationResponse result) {
        if (result.getImages().isEmpty()) {
            Log.d("ImageEditor", "No images generated");
        }
        Bitmap editedImage = result.getImages().get(0).asBitmap();
        // Process and use the bitmap to display the image in your UI
    }

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

Web

Imagen 모델을 사용한 이미지 편집은 웹 앱에서 지원되지 않습니다. 올해 다시 확인해 주세요.

Dart

제공된 마스크를 사용하여 배경을 바꾸려면 마스크 처리된 이미지와 함께 ImagenRawMask을 지정합니다. editImage()를 사용하여 편집 구성이 ImagenEditMode.INPAINT_INSERTION를 사용하도록 설정합니다.

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 'originalImage' is a pre-loaded Uint8List.
// In a real app, this might come from the user's device or a URL.
final Uint8List originalImage = Uint8List(0); // TODO: Load your original image data here.

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

// Provide the prompt describing the new background.
final prompt = 'space background';

try {
  // Use the editImage API to replace the background.
  // Pass the original image, the prompt, and an editing configuration.
  final response = await model.editImage(
    sources: [
      ImagenRawImage(originalImage),
      ImagenRawMask(maskImage), // Use ImagenRawMask() to provide your own masked image.
    ],
    prompt: prompt,
    // Define the editing configuration for inpainting and background replacement.
    config: const ImagenEditingConfig(
      editMode: ImagenEditMode.inpaintInsertion,
    ),
  );

  // 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 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.

권장사항 및 제한사항

이미지를 수정할 때는 마스크를 확장하는 것이 좋습니다. 이렇게 하면 수정사항의 테두리를 부드럽게 처리하여 더 설득력 있게 만들 수 있습니다. 일반적으로 1% 또는 2% 의 팽창 값이 권장됩니다 (0.01 또는 0.02).


Firebase AI Logic 사용 경험에 관한 의견 보내기