인페인트를 사용하여 이미지에 객체 삽입

이 페이지에서는 이미지에 객체를 삽입하는 방법(인페인팅이라고도 함)을 설명합니다. Vertex AI 기반 Imagen을 사용하면 마스크 영역을 지정하여 이미지에 객체를 삽입할 수 있습니다. 자체 마스크를 가져오거나 Vertex AI 기반 Imagen을 사용하여 자동으로 마스크를 생성할 수 있습니다.

콘텐츠 삽입 예

콘텐츠를 삽입하기 위해 인페인팅을 사용하면 기본 이미지, 이미지 마스크, 텍스트 프롬프트를 사용하여 콘텐츠를 기존 이미지에 추가할 수 있습니다.

입력

수정할 기본 이미지* Google Cloud 콘솔에서 도구를 사용하여 지정한 마스크 영역 텍스트 프롬프트
기본 이미지의 예입니다. 유리병에 빨간색 액체가 들어 있고, 옆에는 레몬 조각이 있으며 빨대가 꽂혀 있습니다. 레몬 슬라이스가 왼쪽 전경에 표시됩니다. 이제 Cloud 콘솔에 마스크 영역이 지정된 유리병의 기본 이미지 딸기

* 이미지 출처: Unsplash알렉스 르비어스

Google Cloud 콘솔에서 마스크 영역을 지정한 후 출력

빨간색 액체가 들어 있는 유리병의 생성된 수정 버전의 스크린샷 이 스크린샷에서는 이전에 이미지 전경에 있던 레몬 조각이 병 바로 앞에 있는 딸기 두 개로 대체되었습니다. 빨간색 액체가 들어 있는 유리병의 생성된 수정 버전의 스크린샷 이 스크린샷에서는 이전에 이미지 전경에 있던 레몬 조각이 병 바로 왼쪽에 있는 딸기 3개로 대체되었습니다. 빨간색 액체가 들어 있는 유리병의 생성된 수정 버전의 스크린샷 이 스크린샷에서는 이미지 포그라운드에 있던 레몬 조각이 항아리 앞쪽 왼쪽의 딸기 두 개로 대체되었습니다.

수정 및 맞춤설정을 위한 Imagen 모델 카드 보기

시작하기 전에

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

  8. 환경에 대한 인증을 설정하세요.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    Java

    로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    Node.js

    로컬 개발 환경에서 이 페이지의 Node.js 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    Python

    로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.

    REST

    로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공한 사용자 인증 정보를 사용합니다.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    자세한 내용은 Google Cloud 인증 문서의 REST 사용을 위한 인증을 참조하세요.

    정의된 마스크 영역으로 삽입

    다음 샘플을 사용하여 콘텐츠를 삽입할 인페인팅을 지정합니다. 다음 샘플에서는 기본 이미지, 텍스트 프롬프트, 기본 이미지를 수정할 마스크 영역을 지정합니다.

    Imagen 3

    다음 샘플을 사용하여 Imagen 3 모델을 사용한 인페인팅 요청을 전송합니다.

    콘솔

    1. Google Cloud 콘솔에서 Vertex AI > Media Studio 페이지로 이동합니다.

      Media Studio로 이동

    2. 업로드를 클릭합니다. 표시된 파일 대화상자에서 업로드할 파일을 선택합니다.
    3. 인페인트를 클릭합니다.
    4. 다음 중 하나를 수행합니다.

      • 자체 마스크를 업로드합니다
        1. 컴퓨터에서 마스크를 만듭니다.
        2. 마스크 업로드를 클릭합니다. 표시된 대화상자에서 업로드할 마스크를 선택합니다.
      • 마스크 정의: 수정 툴바에서 마스크 도구(상자, 브러시 또는 masked_transitions 반전 도구)를 사용하여 콘텐츠를 추가할 영역을 지정합니다.
    5. 선택사항: 파라미터 패널에서 다음 옵션을 조정합니다.
      • 모델: 사용할 Imagen 모델
      • 결과 수: 생성할 결과 수
      • 부정 프롬프트: 생성하지 말아야 할 항목
    6. 프롬프트 필드에 프롬프트를 입력하여 이미지를 수정합니다.
    7. 생성을 클릭합니다.

    Python

    설치

    pip install --upgrade google-genai

    자세한 내용은 SDK 참고 문서를 참조하세요.

    Vertex AI에서 Gen AI SDK를 사용하도록 환경 변수를 설정합니다.

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=us-central1
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import RawReferenceImage, MaskReferenceImage, MaskReferenceConfig, EditImageConfig
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_file = "output-image.png"
    
    raw_ref = RawReferenceImage(
        reference_image=Image.from_file(location='test_resources/fruit.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=Image.from_file(location='test_resources/fruit_mask.png'),
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_USER_PROVIDED",
            mask_dilation=0.01,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A plate of cookies",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_INPAINT_INSERTION",
        ),
    )
    
    image.generated_images[0].image.save(output_file)
    
    print(f"Created output image using {len(image.generated_images[0].image.image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes
    

    REST

    자세한 내용은 이미지 수정 API 참조를 확인하세요.

    요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID
    • LOCATION: 프로젝트의 리전. 예를 들면 us-central1, europe-west2, asia-northeast3입니다. 사용 가능한 리전 목록은 Vertex AI의 생성형 AI 위치를 참조하세요.
    • TEXT_PROMPT: 모델이 생성하는 이미지를 안내하는 텍스트 프롬프트. 인페인팅 삽입에 프롬프트를 사용할 때는 마스킹된 영역에 대한 설명을 사용하면 최상의 결과를 얻을 수 있습니다. 한 단어 프롬프트는 사용하지 마세요. 예를 들어 "코기" 대신 "귀여운 코기"를 사용하세요.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • B64_MASK_IMAGE: 원본 이미지를 수정하기 위해 마스크 레이어로 사용할 흑백 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • MASK_DILATION - 부동 소수점 수. 이 마스크를 확장할 이미지 너비의 비율입니다. 불완전한 입력 마스크를 보완하려면 0.01 값을 사용하는 것이 좋습니다.
    • EDIT_STEPS - 정수. 기본 모델의 샘플링 단계 수입니다. 인페인팅 삽입의 경우 35 단계부터 시작합니다. 품질이 요구사항을 충족하지 않으면 단계를 상한선인 75로 늘립니다. 단계를 늘리면 요청 지연 시간도 늘어납니다.
    • EDIT_IMAGE_COUNT: 수정된 이미지의 수. 허용되는 정수 값: 1~4. 기본값: 4.

    HTTP 메서드 및 URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict

    JSON 요청 본문:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "referenceImages": [
            {
              "referenceType": "REFERENCE_TYPE_RAW",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "B64_BASE_IMAGE"
              }
            },
            {
              "referenceType": "REFERENCE_TYPE_MASK",
              "referenceId": 2,
              "referenceImage": {
                "bytesBase64Encoded": "B64_MASK_IMAGE"
              },
              "maskImageConfig": {
                "maskMode": "MASK_MODE_USER_PROVIDED",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_INPAINT_INSERTION",
        "sampleCount": EDIT_IMAGE_COUNT
      }
    }
    

    요청을 보내려면 다음 옵션 중 하나를 선택합니다.

    curl

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict"

    PowerShell

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict" | Select-Object -Expand Content
    다음은 "sampleCount": 2 요청에 대한 샘플 응답입니다. 응답은 생성된 이미지 바이트를 base64로 인코딩한 두 개의 예측 객체를 반환합니다.
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    Imagen 2

    다음 샘플을 사용하여 Imagen 2 모델을 사용한 인페인팅 요청을 전송합니다.

    콘솔

    1. Google Cloud 콘솔에서 Vertex AI > Media Studio 페이지로 이동합니다.

      Media Studio로 이동

    2. 업로드를 클릭합니다. 표시된 파일 대화상자에서 업로드할 파일을 선택합니다.
    3. 인페인트를 클릭합니다.
    4. 다음 중 하나를 수행합니다.

      • 자체 마스크를 업로드합니다
        1. 컴퓨터에서 마스크를 만듭니다.
        2. 마스크 업로드를 클릭합니다. 표시된 대화상자에서 업로드할 마스크를 선택합니다.
      • 마스크 정의: 수정 툴바에서 마스크 도구(상자, 브러시 또는 masked_transitions반전 도구)를 사용하여 콘텐츠를 추가할 영역을 지정합니다.
    5. (선택사항) 매개변수 패널에서 다음 옵션을 조정합니다.
      • 모델: 사용할 Imagen 모델
      • 결과 수: 생성할 결과 수
      • 부정 프롬프트: 생성하지 말아야 할 항목
    6. 프롬프트 필드에 새 프롬프트를 입력하여 이미지를 수정합니다.
    7. 생성을 클릭합니다.

    Python

    Vertex AI SDK for Python을 설치하거나 업데이트하는 방법은 Vertex AI SDK for Python 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

    
    import vertexai
    from vertexai.preview.vision_models import Image, ImageGenerationModel
    
    # TODO(developer): Update and un-comment below lines
    # PROJECT_ID = "your-project-id"
    # input_file = "input-image.png"
    # mask_file = "mask-image.png"
    # output_file = "output-image.png"
    # prompt = "red hat" # The text prompt describing what you want to see inserted.
    
    vertexai.init(project=PROJECT_ID, location="us-central1")
    
    model = ImageGenerationModel.from_pretrained("imagegeneration@006")
    base_img = Image.load_from_file(location=input_file)
    mask_img = Image.load_from_file(location=mask_file)
    
    images = model.edit_image(
        base_image=base_img,
        mask=mask_img,
        prompt=prompt,
        edit_mode="inpainting-insert",
    )
    
    images[0].save(location=output_file, include_generation_parameters=False)
    
    # Optional. View the edited image in a notebook.
    # images[0].show()
    
    print(f"Created output image using {len(images[0]._image_bytes)} bytes")
    # Example response:
    # Created output image using 1400814 bytes
    

    REST

    imagegeneration 모델 요청에 대한 자세한 내용은 imagegeneration 모델 API 참조를 확인하세요.

    요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID
    • LOCATION: 프로젝트의 리전. 예를 들면 us-central1, europe-west2, asia-northeast3입니다. 사용 가능한 리전 목록은 Vertex AI의 생성형 AI 위치를 참조하세요.
    • TEXT_PROMPT: 모델이 생성하는 이미지를 안내하는 텍스트 프롬프트. 이 필드는 생성 및 수정 모두에서 필요합니다.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • B64_MASK_IMAGE: 원본 이미지를 수정하기 위해 마스크 레이어로 사용할 흑백 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • EDIT_IMAGE_COUNT: 수정된 이미지의 수. 기본값: 4
    • GUIDANCE_SCALE_VALUE: 모델에서 텍스트 프롬프트를 준수하는 정도를 제어하는 파라미터(정수)입니다. 값이 클수록 텍스트 프롬프트와 생성된 이미지 간의 정렬이 증가하지만 이미지 품질이 저하될 수 있습니다. 값은 0~500입니다. 기본값: 60

    HTTP 메서드 및 URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict

    JSON 요청 본문:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "image": {
              "bytesBase64Encoded": "B64_BASE_IMAGE"
          },
          "mask": {
            "image": {
              "bytesBase64Encoded": "B64_MASK_IMAGE"
            }
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "inpainting-insert",
          "guidanceScale": GUIDANCE_SCALE_VALUE
        }
      }
    }
    

    요청을 보내려면 다음 옵션 중 하나를 선택합니다.

    curl

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict"

    PowerShell

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict" | Select-Object -Expand Content
    다음은 "sampleCount": 2 요청에 대한 샘플 응답입니다. 응답은 생성된 이미지 바이트를 base64로 인코딩한 두 개의 예측 객체를 반환합니다.
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    Java

    이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

    Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

    이 샘플에서는 EndpointName의 일부로 모델을 지정합니다. EndpointNamePredictionServiceClient에서 호출되는 predict 메서드에 전달됩니다. 이 서비스는 이미지의 수정된 버전을 반환한 다음 로컬에 저장합니다

    모델 버전과 기능에 대한 자세한 내용은 Imagen 모델을 참조하세요.

    
    import com.google.api.gax.rpc.ApiException;
    import com.google.cloud.aiplatform.v1.EndpointName;
    import com.google.cloud.aiplatform.v1.PredictResponse;
    import com.google.cloud.aiplatform.v1.PredictionServiceClient;
    import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
    import com.google.gson.Gson;
    import com.google.protobuf.InvalidProtocolBufferException;
    import com.google.protobuf.Value;
    import com.google.protobuf.util.JsonFormat;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Base64;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    
    public class EditImageInpaintingInsertMaskSample {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "my-project-id";
        String location = "us-central1";
        String inputPath = "/path/to/my-input.png";
        String maskPath = "/path/to/my-mask.png";
        String prompt =
            ""; // The text prompt describing what you want to see inserted in the mask area.
    
        editImageInpaintingInsertMask(projectId, location, inputPath, maskPath, prompt);
      }
    
      // Edit an image using a mask file. Inpainting can insert the object designated by the prompt
      // into the masked area.
      public static PredictResponse editImageInpaintingInsertMask(
          String projectId, String location, String inputPath, String maskPath, String prompt)
          throws ApiException, IOException {
        final String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
        PredictionServiceSettings predictionServiceSettings =
            PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();
    
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (PredictionServiceClient predictionServiceClient =
            PredictionServiceClient.create(predictionServiceSettings)) {
    
          final EndpointName endpointName =
              EndpointName.ofProjectLocationPublisherModelName(
                  projectId, location, "google", "imagegeneration@006");
    
          // Encode image and mask to Base64
          String imageBase64 =
              Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(inputPath)));
          String maskBase64 =
              Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(maskPath)));
    
          // Create the image and image mask maps
          Map<String, String> imageMap = new HashMap<>();
          imageMap.put("bytesBase64Encoded", imageBase64);
    
          Map<String, String> maskMap = new HashMap<>();
          maskMap.put("bytesBase64Encoded", maskBase64);
          Map<String, Map> imageMaskMap = new HashMap<>();
          imageMaskMap.put("image", maskMap);
    
          Map<String, Object> instancesMap = new HashMap<>();
          instancesMap.put("prompt", prompt); // [ "prompt", "<my-prompt>" ]
          instancesMap.put(
              "image", imageMap); // [ "image", [ "bytesBase64Encoded", "iVBORw0KGgo...==" ] ]
          instancesMap.put(
              "mask",
              imageMaskMap); // [ "mask", [ "image", [ "bytesBase64Encoded", "iJKDF0KGpl...==" ] ] ]
          instancesMap.put("editMode", "inpainting-insert"); // [ "editMode", "inpainting-insert" ]
          Value instances = mapToValue(instancesMap);
    
          // Optional parameters
          Map<String, Object> paramsMap = new HashMap<>();
          paramsMap.put("sampleCount", 1);
          Value parameters = mapToValue(paramsMap);
    
          PredictResponse predictResponse =
              predictionServiceClient.predict(
                  endpointName, Collections.singletonList(instances), parameters);
    
          for (Value prediction : predictResponse.getPredictionsList()) {
            Map<String, Value> fieldsMap = prediction.getStructValue().getFieldsMap();
            if (fieldsMap.containsKey("bytesBase64Encoded")) {
              String bytesBase64Encoded = fieldsMap.get("bytesBase64Encoded").getStringValue();
              Path tmpPath = Files.createTempFile("imagen-", ".png");
              Files.write(tmpPath, Base64.getDecoder().decode(bytesBase64Encoded));
              System.out.format("Image file written to: %s\n", tmpPath.toUri());
            }
          }
          return predictResponse;
        }
      }
    
      private static Value mapToValue(Map<String, Object> map) throws InvalidProtocolBufferException {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        Value.Builder builder = Value.newBuilder();
        JsonFormat.parser().merge(json, builder);
        return builder.build();
      }
    }
    

    Node.js

    이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

    Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

    이 샘플에서는 PredictionServiceClient에서 predict 메서드를 호출합니다. 이 서비스는 로컬로 저장되는 이미지를 생성합니다. 모델 버전과 기능에 대한 자세한 내용은 Imagen 모델을 참조하세요.

    /**
     * TODO(developer): Update these variables before running the sample.
     */
    const projectId = process.env.CAIP_PROJECT_ID;
    const location = 'us-central1';
    const inputFile = 'resources/woman.png';
    const maskFile = 'resources/woman_inpainting_insert_mask.png';
    const prompt = 'hat';
    
    const aiplatform = require('@google-cloud/aiplatform');
    
    // Imports the Google Cloud Prediction Service Client library
    const {PredictionServiceClient} = aiplatform.v1;
    
    // Import the helper module for converting arbitrary protobuf.Value objects
    const {helpers} = aiplatform;
    
    // Specifies the location of the api endpoint
    const clientOptions = {
      apiEndpoint: `${location}-aiplatform.googleapis.com`,
    };
    
    // Instantiates a client
    const predictionServiceClient = new PredictionServiceClient(clientOptions);
    
    async function editImageInpaintingInsertMask() {
      const fs = require('fs');
      const util = require('util');
      // Configure the parent resource
      const endpoint = `projects/${projectId}/locations/${location}/publishers/google/models/imagegeneration@006`;
    
      const imageFile = fs.readFileSync(inputFile);
      // Convert the image data to a Buffer and base64 encode it.
      const encodedImage = Buffer.from(imageFile).toString('base64');
    
      const maskImageFile = fs.readFileSync(maskFile);
      // Convert the image mask data to a Buffer and base64 encode it.
      const encodedMask = Buffer.from(maskImageFile).toString('base64');
    
      const promptObj = {
        prompt: prompt, // The text prompt describing what you want to see inserted
        editMode: 'inpainting-insert',
        image: {
          bytesBase64Encoded: encodedImage,
        },
        mask: {
          image: {
            bytesBase64Encoded: encodedMask,
          },
        },
      };
      const instanceValue = helpers.toValue(promptObj);
      const instances = [instanceValue];
    
      const parameter = {
        // Optional parameters
        seed: 100,
        // Controls the strength of the prompt
        // 0-9 (low strength), 10-20 (medium strength), 21+ (high strength)
        guidanceScale: 21,
        sampleCount: 1,
      };
      const parameters = helpers.toValue(parameter);
    
      const request = {
        endpoint,
        instances,
        parameters,
      };
    
      // Predict request
      const [response] = await predictionServiceClient.predict(request);
      const predictions = response.predictions;
      if (predictions.length === 0) {
        console.log(
          'No image was generated. Check the request parameters and prompt.'
        );
      } else {
        let i = 1;
        for (const prediction of predictions) {
          const buff = Buffer.from(
            prediction.structValue.fields.bytesBase64Encoded.stringValue,
            'base64'
          );
          // Write image content to the output file
          const writeFile = util.promisify(fs.writeFile);
          const filename = `output${i}.png`;
          await writeFile(filename, buff);
          console.log(`Saved image ${filename}`);
          i++;
        }
      }
    }
    await editImageInpaintingInsertMask();

    자동 마스크 감지를 사용하여 삽입

    다음 샘플을 사용하여 콘텐츠를 삽입할 인페인팅을 지정합니다. 다음 샘플에서는 기본 이미지와 텍스트 프롬프트를 지정합니다. Imagen은 기본 이미지를 수정할 마스크 영역을 자동으로 감지하고 만듭니다.

    Imagen 3

    다음 샘플을 사용하여 Imagen 3 모델을 사용한 인페인팅 요청을 전송합니다.

    콘솔

    1. Google Cloud 콘솔에서 Vertex AI > Media Studio 페이지로 이동합니다.

      Media Studio로 이동

    2. 업로드를 클릭합니다. 표시된 파일 대화상자에서 업로드할 파일을 선택합니다.
    3. 인페인트를 클릭합니다.
    4. 수정 툴바에서 background_replace마스크 추출을 클릭합니다.
    5. 마스크 추출 옵션 중 하나를 선택합니다.

      • 백그라운드 요소: 백그라운드 요소를 감지하고 요소 주위에 마스크를 만듭니다.
      • 포그라운드 요소: 포그라운드 객체를 감지하고 객체 주위에 마스크를 만듭니다.
      • background_replace 사람: 사람을 감지하고 사람 주위에 마스크를 만듭니다.
    6. 선택사항: 파라미터 패널에서 다음 옵션을 조정합니다.
      • 모델: 사용할 Imagen 모델
      • 결과 수: 생성할 결과 수
      • 부정 프롬프트: 생성하지 말아야 할 항목
    7. 프롬프트 필드에 새 프롬프트를 입력하여 이미지를 수정합니다.
    8. send 생성을 클릭합니다.

    Python

    설치

    pip install --upgrade google-genai

    자세한 내용은 SDK 참고 문서를 참조하세요.

    Vertex AI에서 Gen AI SDK를 사용하도록 환경 변수를 설정합니다.

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=us-central1
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import RawReferenceImage, MaskReferenceImage, MaskReferenceConfig, EditImageConfig
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_file = "output-image.png"
    
    raw_ref = RawReferenceImage(
        reference_image=Image.from_file(location='test_resources/fruit.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=None,
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_FOREGROUND",
            mask_dilation=0.1,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A small white ceramic bowl with lemons and limes",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_INPAINT_INSERTION",
        ),
    )
    
    image.generated_images[0].image.save(output_file)
    
    print(f"Created output image using {len(image.generated_images[0].image.image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes
    

    REST

    자세한 내용은 이미지 수정 API 참조를 확인하세요.

    요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID
    • LOCATION: 프로젝트의 리전. 예를 들면 us-central1, europe-west2, asia-northeast3입니다. 사용 가능한 리전 목록은 Vertex AI의 생성형 AI 위치를 참조하세요.
    • TEXT_PROMPT: 모델이 생성하는 이미지를 안내하는 텍스트 프롬프트. 인페인팅 삽입에 프롬프트를 사용할 때는 마스킹된 영역에 대한 설명을 사용하면 최상의 결과를 얻을 수 있습니다. 한 단어 프롬프트는 사용하지 마세요. 예를 들어 "코기" 대신 "귀여운 코기"를 사용하세요.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • MASK_MODE - 모델에 사용되는 자동 마스크 생성 유형을 설정하는 문자열입니다. 사용 가능한 값은 다음과 같습니다.
      • MASK_MODE_BACKGROUND: 배경 세분화를 사용하여 마스크를 자동으로 생성합니다.
      • MASK_MODE_FOREGROUND: 전경 세분화를 사용하여 마스크를 자동으로 생성합니다.
      • MASK_MODE_SEMANTIC: maskImageConfig.maskClasses 배열에 지정한 세분화 클래스를 기반으로 시맨틱 세분화를 사용하여 마스크를 자동으로 생성합니다. 예를 들면 다음과 같습니다.
                  "maskImageConfig": {
                    "maskMode": "MASK_MODE_SEMANTIC",
                    "maskClasses": [175, 176], // bicycle, car
                    "dilation": 0.01
                  }
                
    • MASK_DILATION - 부동 소수점 수. 이 마스크를 확장할 이미지 너비의 비율입니다. 불완전한 입력 마스크를 보완하려면 0.01 값을 사용하는 것이 좋습니다.
    • EDIT_STEPS - 정수. 기본 모델의 샘플링 단계 수입니다. 인페인팅 삽입의 경우 35 단계부터 시작합니다. 품질이 요구사항을 충족하지 않으면 단계를 상한선인 75로 늘립니다. 단계를 늘리면 요청 지연 시간도 늘어납니다.
    • EDIT_IMAGE_COUNT: 수정된 이미지의 수. 허용되는 정수 값: 1~4. 기본값: 4.

    HTTP 메서드 및 URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict

    JSON 요청 본문:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "referenceImages": [
            {
              "referenceType": "REFERENCE_TYPE_RAW",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "B64_BASE_IMAGE"
              }
            },
            {
              "referenceType": "REFERENCE_TYPE_MASK",
              "referenceId": 2,
              "maskImageConfig": {
                "maskMode": "MASK_MODE",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_INPAINT_INSERTION",
        "sampleCount": EDIT_IMAGE_COUNT
      }
    }
    

    요청을 보내려면 다음 옵션 중 하나를 선택합니다.

    curl

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict"

    PowerShell

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict" | Select-Object -Expand Content
    다음은 "sampleCount": 2 요청에 대한 샘플 응답입니다. 응답은 생성된 이미지 바이트를 base64로 인코딩한 두 개의 예측 객체를 반환합니다.
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    Imagen 2

    다음 샘플을 사용하여 Imagen 2 모델을 사용한 인페인팅 요청을 전송합니다.

    콘솔

    1. Google Cloud 콘솔에서 Vertex AI > Media Studio 페이지로 이동합니다.

      Media Studio로 이동

    2. 하단 태스크 패널에서 이미지 수정을 클릭합니다.

    3. 업로드를 클릭하여 로컬에 저장된 이미지를 선택해 수정합니다.

    4. 수정 툴바에서 background_replace추출을 클릭합니다.

    5. 마스크 추출 옵션 중 하나를 선택합니다.

      • 배경 요소 - 배경 요소를 감지하고 요소 주위에 마스크를 만듭니다.
      • 포그라운드 요소 - 포그라운드 객체를 감지하고 객체 주위에 마스크를 만듭니다.
      • background_replace사람 - 사람을 감지하고 사람 주위에 마스크를 만듭니다.
    6. 선택사항: 파라미터 패널에서 결과 수, 부정 프롬프트, 텍스트 프롬프트 안내 또는 기타 파라미터를 조정합니다.

    7. 프롬프트 필드에 프롬프트를 입력하여 이미지를 수정합니다.

    8. 생성을 클릭합니다.

    Python

    Vertex AI SDK for Python을 설치하거나 업데이트하는 방법은 Vertex AI SDK for Python 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

    
    import vertexai
    from vertexai.preview.vision_models import Image, ImageGenerationModel
    
    # TODO(developer): Update and un-comment below lines
    # PROJECT_ID = "your-project-id"
    # input_file = "input-image.png"
    # mask_mode = "background" # 'background', 'foreground', or 'semantic'
    # output_file = "output-image.png"
    # prompt = "beach" # The text prompt describing what you want to see inserted.
    
    vertexai.init(project=PROJECT_ID, location="us-central1")
    
    model = ImageGenerationModel.from_pretrained("imagegeneration@006")
    base_img = Image.load_from_file(location=input_file)
    
    images = model.edit_image(
        base_image=base_img,
        mask_mode=mask_mode,
        prompt=prompt,
        edit_mode="inpainting-insert",
    )
    
    images[0].save(location=output_file, include_generation_parameters=False)
    
    # Optional. View the edited image in a notebook.
    # images[0].show()
    
    print(f"Created output image using {len(images[0]._image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes
    

    REST

    imagegeneration 모델 요청에 대한 자세한 내용은 imagegeneration 모델 API 참조를 확인하세요.

    요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID
    • LOCATION: 프로젝트의 리전. 예를 들면 us-central1, europe-west2, asia-northeast3입니다. 사용 가능한 리전 목록은 Vertex AI의 생성형 AI 위치를 참조하세요.
    • TEXT_PROMPT: 모델이 생성하는 이미지를 안내하는 텍스트 프롬프트. 이 필드는 생성 및 수정 모두에서 필요합니다.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • EDIT_IMAGE_COUNT: 수정된 이미지의 수. 기본값: 4
    • MASK_TYPE: 마스크를 제공할 필요 없이 마스크를 생성하라고 모델에게 지시합니다. 따라서 이 파라미터를 제공할 때는 mask 객체를 생략해야 합니다. 사용 가능한 값은 다음과 같습니다.
      • background: 이미지에서 기본 객체, 사람 또는 주체를 제외한 모든 리전에 대한 마스크를 자동으로 생성합니다.
      • foreground: 이미지의 기본 객체, 사람 또는 주체에 대한 마스크를 자동으로 생성합니다.
      • semantic: 자동 세분화를 사용하여 세분화 클래스 하나 이상에 마스크 영역을 만듭니다. classes 파라미터와 해당 class_id 값을 사용하여 세분화 클래스를 설정합니다. 클래스를 최대 5개까지 지정할 수 있습니다. 시맨틱 마스크 유형을 사용하는 경우 maskMode 객체는 다음과 같이 표시됩니다.
        "maskMode": {
          "maskType": "semantic",
          "classes": [class_id1, class_id2]
        }
    • GUIDANCE_SCALE_VALUE: 모델에서 텍스트 프롬프트를 준수하는 정도를 제어하는 파라미터(정수)입니다. 값이 클수록 텍스트 프롬프트와 생성된 이미지 간의 정렬이 증가하지만 이미지 품질이 저하될 수 있습니다. 값은 0~500입니다. 기본값: 60

    HTTP 메서드 및 URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict

    JSON 요청 본문:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "image": {
            "bytesBase64Encoded": "B64_BASE_IMAGE"
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "inpainting-insert",
          "maskMode": {
            "maskType": "MASK_TYPE"
          },
          "guidanceScale": GUIDANCE_SCALE_VALUE
        }
      }
    }
    

    요청을 보내려면 다음 옵션 중 하나를 선택합니다.

    curl

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict"

    PowerShell

    요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict" | Select-Object -Expand Content
    다음은 "sampleCount": 2 요청에 대한 샘플 응답입니다. 응답은 생성된 이미지 바이트를 base64로 인코딩한 두 개의 예측 객체를 반환합니다.
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    제한사항

    다음 섹션에서는 Imagen의 객체 삭제 기능 제한사항을 설명합니다.

    수정된 픽셀

    모델에서 생성되었으나 마스크에 없는 픽셀은 입력과 동일하지 않을 수 있으며 모델 해상도(예: 1024x1024)로 생성됩니다. 생성된 이미지에 아주 미세한 변경사항이 있을 수 있습니다.

    이미지를 완벽하게 보존하려면 마스크를 사용하여 생성된 이미지를 입력 이미지와 혼합하는 것이 좋습니다. 일반적으로 입력 이미지 해상도가 2K 이상이면 생성된 이미지와 입력 이미지를 혼합해야 합니다.

    제한사항 삽입

    삽입은 일반적으로 기본 이미지 스타일과 일치합니다. 하지만 사실적인 출력을 만들려고 해도 특정 키워드로 인해 만화 스타일과 유사한 출력이 트리거될 수 있습니다.

    특히 부정확한 색상이 한 가지 예입니다. 예를 들어 사실적인 기린은 갈색과 황갈색이므로 '노란색 기린'은 만화 기린을 생성하는 경향이 있습니다. 마찬가지로 사실적이지만 부자연스러운 색상을 생성하기는 어렵습니다.

    다음 단계

    Imagen 및 Vertex AI의 기타 생성형 AI 제품 관련 문서 읽기: