이 페이지에서는 Imagen를 사용하여 Firebase AI Logic SDK로 이미지에서 객체를 삭제하는 인페인팅을 사용하는 방법을 설명합니다.
인페인팅은 마스크 기반 수정의 일종입니다. 마스크는 수정할 특정 영역을 정의하는 디지털 오버레이입니다.
작동 방식: 원본 이미지와 해당 마스크 이미지(자동 생성 또는 사용자가 제공)를 제공합니다. 이 이미지는 삭제하려는 객체 또는 주체에 대한 마스크를 정의합니다. 삭제하려는 항목을 설명하는 텍스트 프롬프트를 선택적으로 제공할 수도 있고, 모델이 삭제할 객체를 지능적으로 감지할 수도 있습니다. 그런 다음 모델이 객체를 삭제하고 맥락에 적합한 새 콘텐츠로 영역을 채웁니다.
예를 들어 공을 마스크 처리하고 빈 벽이나 잔디밭으로 바꿀 수 있습니다.
자동 생성 마스크의 코드로 이동 마스크 제공 코드로 이동
시작하기 전에
Vertex AI Gemini API을 API 제공자로 사용하는 경우에만 사용할 수 있습니다. |
아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 API 제공업체의 백엔드 서비스를 초기화하고, ImagenModel
인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료합니다.
이 기능을 지원하는 모델
Imagen는 capability
모델을 통해 이미지 편집을 제공합니다.
imagen-3.0-capability-001
Imagen 모델의 경우 global
위치는 지원되지 않습니다.
자동 생성된 마스크를 사용하여 객체 삭제
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. |
다음 샘플은 자동 마스크 생성을 사용하여 인페인팅으로 이미지에서 콘텐츠를 삭제하는 방법을 보여줍니다. 원본 이미지와 텍스트 프롬프트를 제공하면 Imagen이 원본 이미지를 수정할 마스크 영역을 자동으로 감지하고 만듭니다.
Swift
Swift에서는 Imagen 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.
Kotlin
자동 생성된 마스크로 객체를 삭제하려면 ImagenBackgroundMask
를 지정합니다. editImage()
를 사용하여 편집 구성이 ImagenEditMode.INPAINT_REMOVAL
를 사용하도록 설정합니다.
// 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 content to be removed.
val prompt = "ball"
// Use the editImage API to remove the unwanted content.
// 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 insertion.
config = ImagenEditingConfig(ImagenEditMode.INPAINT_REMOVAL)
)
// Process the resulting 'editedImage' Bitmap, for example, by displaying it in an ImageView.
}
Java
자동 생성된 마스크로 객체를 삭제하려면 ImagenBackgroundMask
를 지정합니다. editImage()
를 사용하여 편집 구성이 ImagenEditMode.INPAINT_REMOVAL
를 사용하도록 설정합니다.
// 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 content to be removed.
String prompt = "ball";
// 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 removal.
ImagenEditingConfig config = new ImagenEditingConfig.Builder()
.setEditMode(ImagenEditMode.INPAINT_REMOVAL)
.build();
// Use the editImage API to remove the unwanted content.
// 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.inpaintRemoval
를 사용하도록 설정합니다.
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');
TODO - FLUTTER// 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 content to be removed.
final prompt = 'ball';
try {
// Use the editImage API to remove the unwanted content.
// 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,
// Define the editing configuration for inpainting and removal.
config: const ImagenEditingConfig(
editMode: ImagenEditMode.inpaintRemoval,
),
);
// 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 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.
제공된 마스크를 사용하여 객체 삭제
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. |
다음 샘플은 제공한 이미지에 정의된 마스크를 사용하여 인페인팅으로 이미지에서 콘텐츠를 삭제하는 방법을 보여줍니다. 원본 이미지, 텍스트 프롬프트, 마스크 처리된 이미지를 제공합니다.
마스크 처리된 이미지를 제공하는 경우 텍스트 프롬프트는 선택사항입니다. Imagen는 마스크 처리된 영역에서 삭제할 객체를 지능적으로 감지할 수 있습니다. 하지만 삭제하려는 객체가 명확하지 않거나 마스크 처리된 영역에서 특정 객체만 삭제하려는 경우 모델이 올바른 객체를 삭제할 수 있도록 텍스트 프롬프트를 제공하세요.
Swift
Swift에서는 Imagen 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.
Kotlin
객체를 삭제하고 자체 마스크 이미지를 제공하려면 마스크 이미지와 함께 ImagenRawMask
를 지정하세요. editImage()
를 사용하여 편집 구성이 ImagenEditMode.INPAINT_REMOVAL
를 사용하도록 설정합니다.
// 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 content to be removed.
val prompt = "ball"
// Use the editImage API to remove the unwanted content.
// 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 removal.
config = ImagenEditingConfig(ImagenEditMode.INPAINT_REMOVAL)
)
// Process the resulting 'editedImage' Bitmap, for example, by displaying it in an ImageView.
}
Java
객체를 삭제하고 자체 마스크 이미지를 제공하려면 마스크 이미지와 함께 ImagenRawMask
를 지정하세요. editImage()
를 사용하여 편집 구성이 ImagenEditMode.INPAINT_REMOVAL
를 사용하도록 설정합니다.
// 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 content to be removed.
String prompt = "ball";
// 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 removal.
ImagenEditingConfig config = new ImagenEditingConfig.Builder()
.setEditMode(ImagenEditMode.INPAINT_REMOVAL)
.build();
// Use the editImage API to remove the unwanted content.
// 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.inpaintRemoval
를 사용하도록 설정합니다.
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 content to be removed.
final prompt = 'ball';
try {
// Use the editImage API to remove the unwanted content.
// 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 removal.
config: const ImagenEditingConfig(
editMode: ImagenEditMode.inpaintRemoval,
),
);
// 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 사용 경험에 관한 의견 보내기