이 페이지에서는 Imagen의 맞춤설정 기능을 사용하여 Firebase AI Logic SDK를 통해 지정된 제어에 따라 이미지를 수정하거나 생성하는 방법을 설명합니다.
작동 방식: 텍스트 프롬프트와 하나 이상의 제어 참조 이미지 (예: 그림 또는 Canny 윤곽선 이미지)를 제공합니다. 모델은 이러한 입력을 사용하여 제어 이미지를 기반으로 새 이미지를 생성합니다.
예를 들어 로켓과 달 그림을 텍스트 프롬프트와 함께 모델에 제공하여 그림을 기반으로 수채화 그림을 만들 수 있습니다.
제어 참조 이미지 유형
제어된 맞춤설정의 참조 이미지는 낙서, 캐니 윤곽선 이미지 또는 얼굴 메시일 수 있습니다.
시작하기 전에
Vertex AI Gemini API을 API 제공자로 사용하는 경우에만 사용할 수 있습니다. |
아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 API 제공업체의 백엔드 서비스를 초기화하고, ImagenModel
인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료합니다.
이 기능을 지원하는 모델
Imagen는 capability
모델을 통해 이미지 편집을 제공합니다.
imagen-3.0-capability-001
Imagen 모델의 경우 global
위치는 지원되지 않습니다.
제어된 맞춤설정 요청 전송
다음 샘플은 제공된 참조 이미지 (이 예에서는 로켓과 달과 같은 우주 그림)를 기반으로 새 이미지를 생성하도록 모델에 요청하는 제어된 맞춤설정 요청을 보여줍니다. 참조 이미지가 대략적인 손으로 그린 스케치 또는 윤곽선이므로 CONTROL_TYPE_SCRIBBLE
컨트롤 유형을 사용합니다.
참조 이미지가 Canny edge 이미지 또는 얼굴 메쉬인 경우 다음 변경사항을 적용하여 이 예시를 사용할 수도 있습니다.
참고 이미지가 캐니 윤곽선 이미지인 경우 컨트롤 유형
CONTROL_TYPE_CANNY
를 사용합니다.참조 이미지가 얼굴 메쉬인 경우 제어 유형
CONTROL_TYPE_FACE_MESH
를 사용합니다. 이 컨트롤은 인물 주체 맞춤설정에만 사용할 수 있습니다.
이 페이지의 뒷부분에 있는 프롬프트 템플릿을 검토하여 프롬프트를 작성하는 방법과 프롬프트 내에서 참조 이미지를 사용하는 방법을 알아보세요.
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 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
Unity에서는 Imagen 모델을 사용한 이미지 수정이 지원되지 않습니다. 올해 다시 확인해 주세요.
프롬프트 템플릿
요청에서 이미지의 참조 ID를 지정하는 ImagenControlReference
를 정의하여 참고 이미지 (최대 4개)를 제공합니다.
여러 이미지가 동일한 참조 ID를 가질 수 있습니다 (예: 동일한 아이디어의 여러 낙서).
그런 다음 프롬프트를 작성할 때 이러한 ID를 참조합니다. 예를 들어 프롬프트에서 [1]
를 사용하여 참조 ID가 1
인 이미지를 참조합니다.
다음 표에는 컨트롤을 기반으로 맞춤설정을 위한 프롬프트를 작성할 때 시작점으로 사용할 수 있는 프롬프트 템플릿이 나와 있습니다.
사용 사례 | 참조 이미지 | 프롬프트 템플릿 | 예 |
---|---|---|---|
제어된 맞춤설정 | 낙서 지도(1) | 다음 설명과 일치하도록 scribble map [1]에 맞춰 이미지 생성: ${STYLE_PROMPT} ${PROMPT}. | 다음 설명과 일치하도록 scribble map [1]에 맞춰 이미지 생성: 이미지는 편안한 붓 터치가 있는 인상주의 유화 스타일이어야 합니다. 자연광이 비치는 분위기와 눈에 띄는 붓놀림이 특징입니다. 자동차의 사이드뷰입니다. 그의 차는 도시의 불빛이 웅덩이에 반사되는 젖은 반사 노면에 주차되어 있습니다. |
제어된 맞춤설정 | 캐니 컨트롤 이미지(1) | 다음 설명과 일치하도록 edge map [1]에 맞춰 이미지 생성: ${STYLE_PROMPT} ${PROMPT} | 다음 설명과 일치하도록 edge map [1]에 맞춰 이미지 생성. 이미지는 편안한 붓 터치가 있는 인상주의 유화 스타일이어야 합니다. 자연광이 비치는 분위기와 눈에 띄는 붓놀림이 특징입니다. 자동차의 사이드뷰입니다. 그의 차는 도시의 불빛이 웅덩이에 반사되는 젖은 반사 노면에 주차되어 있습니다. |
FaceMesh 입력을 통한 사람 이미지 스타일 지정 |
피사체 이미지(1-3) 얼굴 메시 대조 이미지(1) |
설명과 일치하는 CONTROL_IMAGE [2]의 포즈로 SUBJECT_DESCRIPTION [1]에 관한 이미지를 만들어 줘: SUBJECT_DESCRIPTION [1]의 초상화 ${PROMPT} | 다음 설명과 일치하도록 a woman with short hair [1] 이미지 생성: control image [2]의 포즈를 취한 a woman with short hair [1]의 초상화로 배경이 흐리게 처리된 3D 만화 스타일 카메라를 바라보고 있으며, 미소 짓는 얼굴을 가진 귀엽고 사랑스러운 캐릭터, 파스텔 색조 ... |
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 만화 스타일 이미지 생성: a woman with short hair [1]의 초상화로 배경이 흐리게 처리된 3D 만화 스타일 카메라를 바라보며 미소 짓는 얼굴을 한 귀엽고 사랑스러운 캐릭터, 파스텔 색조 ... |
권장사항 및 제한사항
사용 사례
맞춤설정 기능은 자유 형식의 프롬프트를 제공하므로 모델이 학습된 것보다 더 많은 작업을 할 수 있다는 인상을 줄 수 있습니다. 다음 섹션에서는 맞춤설정의 의도된 사용 사례와 의도하지 않은 사용 사례를 예시를 들어 설명합니다.
의도한 사용 사례에 이 기능을 사용하는 것이 좋습니다. 이러한 사용 사례에 대해 모델을 학습시켰으므로 좋은 결과를 기대할 수 있기 때문입니다. 반대로 의도한 사용 사례를 벗어나는 작업을 모델에 푸시하면 결과가 좋지 않을 수 있습니다.
의도된 사용 사례
다음은 의도된 제어 기반 맞춤설정의 사용 사례입니다.
프롬프트와 캐니 윤곽선 컨트롤 이미지를 따르는 이미지를 생성합니다.
프롬프트와 스크리블 이미지를 따르는 이미지를 생성합니다.
얼굴 표정을 유지하면서 사람의 사진에 스타일을 지정합니다.
의도하지 않은 사용 사례의 예시
다음은 제어를 기반으로 한 맞춤설정의 의도하지 않은 사용 사례의 일부 목록입니다. 이러한 사용 사례에 대해 모델이 학습되지 않았으므로 좋지 않은 결과가 나올 수 있습니다.
프롬프트에 지정된 스타일을 사용하여 이미지를 생성합니다.
참조 이미지에서 제공하는 특정 스타일을 따르는 텍스트에서 이미지를 생성하고 컨트롤 이미지를 사용하여 이미지 구성을 어느 정도 제어합니다.
참조 이미지에서 제공하는 특정 스타일을 따르는 텍스트에서 이미지를 생성하고 컨트롤 낙서를 사용하여 이미지 구성을 어느 정도 제어합니다.
참조 이미지에서 제공하는 특정 스타일을 따르는 텍스트에서 이미지를 생성하고 컨트롤 이미지를 사용하여 이미지 구성을 어느 정도 제어합니다. 이미지 속 인물은 특정 표정을 짓고 있습니다.
두 명 이상의 사람의 사진에 스타일을 지정하고 얼굴 표정을 유지합니다.
반려동물 사진을 스타일화하여 그림으로 변환해 줘. 이미지의 구성을 보존하거나 지정합니다 (예: 수채화).