인페인팅을 사용하여 이미지에 객체 삽입

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

콘텐츠 삽입 예시

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

입력

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

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

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

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

수정 및 맞춤설정을 위한 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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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.

    Python

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

      Google Cloud CLI를 설치합니다.

      외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

      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에 제공한 사용자 인증 정보를 사용합니다.

      Google Cloud CLI를 설치합니다.

      외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

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

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

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

    콘솔

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

    <a href="https://console.cloud.google.com/vertex-ai/studio/media/generate;tab=image" class="button button-primary"
    target="console" track-name="consoleLink" track-type="task">Go to Media
    Studio</a>
    
    1. 업로드를 클릭하고 업로드할 파일을 선택합니다.

    2. 인페인트를 클릭합니다.

      다음 중 하나를 수행합니다.

      • 자체 마스크를 업로드합니다.

        1. 컴퓨터에서 마스크를 만듭니다.

        2. 마스크 업로드를 클릭하고 업로드할 마스크를 선택합니다.

      • 마스크 정의: 수정 툴바에서 마스크 도구(상자, 브러시 또는 masked_transitions 반전 도구)를 사용하여 콘텐츠를 추가할 영역을 지정합니다.

    3. 선택사항: 파라미터 패널에서 다음 옵션을 조정합니다.

      • 모델: 사용할 Imagen 모델

      • 결과 수: 생성할 결과 수

      • 부정 프롬프트: 생성된 이미지에서 제외할 항목을 설명합니다.

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

    5. 생성을 클릭합니다.

    Python

    설치

    pip install --upgrade google-genai

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

    Vertex AI에서 생성형 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

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

    • REGION: 프로젝트가 있는 리전입니다. 지원되는 리전에 대한 자세한 내용은 Vertex AI 위치의 생성형 AI를 참조하세요.
    • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
    • TEXT_PROMPT: 선택사항. 모델이 생성하는 이미지를 안내하는 텍스트 프롬프트입니다. 최상의 결과를 얻으려면 마스킹된 영역의 설명을 사용하고 한 단어 프롬프트는 피하세요. 예를 들어 '코기' 대신 '귀여운 코기'를 사용하세요.
    • B64_BASE_IMAGE: 크기가 10MB 이하인 수정 중인 이미지의 base64 인코딩 이미지입니다. base64 인코딩에 대한 자세한 내용은 Base64 인코딩 및 디코딩 파일을 참조하세요.
    • B64_MASK_IMAGE: 크기가 10MB 이하인 base64 인코딩 흑백 마스크 이미지입니다.
    • MASK_DILATION: 선택사항. 마스크를 확대할 이미지 너비의 비율을 나타내는 0과 1 사이의 부동 소수점 값입니다. dilation을 사용하면 부정확한 마스크를 보완할 수 있습니다. 0.01 값을 사용하는 것이 좋습니다.
    • EDIT_STEPS: (선택사항) 샘플링 단계 수를 나타내는 정수입니다. 값이 클수록 이미지 품질이 우수하고 값이 작을수록 지연 시간이 짧습니다.

      35 단계를 먼저 시도해 보는 것이 좋습니다. 품질이 요구사항을 충족하지 않으면 상한선인 75에 가까운 값으로 늘리는 것이 좋습니다.

    • SAMPLE_COUNT: (선택사항) 생성할 이미지 수를 설명하는 정수입니다. 허용되는 값의 범위는 1~4입니다. 기본값은 4입니다.

    HTTP 메서드 및 URL:

    POST https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/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",
              "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": SAMPLE_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://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/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://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/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은 기본 이미지를 수정할 마스크 영역을 자동으로 감지하고 만듭니다.

    콘솔

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

    <a href="https://console.cloud.google.com/vertex-ai/studio/media/generate;tab=image" class="button button-primary"
    target="console" track-name="consoleLink" track-type="task">Go to Media
    Studio</a>
    
    1. 업로드를 클릭하고 업로드할 파일을 선택합니다.

    2. 인페인트를 클릭합니다.

    3. 수정 툴바에서 background_replace마스크 추출을 클릭합니다.

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

      • 백그라운드 요소: 백그라운드 요소를 감지하고 요소 주위에 마스크를 만듭니다.

      • 포그라운드 요소: 포그라운드 객체를 감지하고 객체 주위에 마스크를 만듭니다.

      • background_replace사람: 사람을 감지하고 사람 주위에 마스크를 만듭니다.

    5. 선택사항: 파라미터 패널에서 다음 옵션을 조정합니다.

      • 모델: 사용할 Imagen 모델

      • 결과 수: 생성할 결과 수

      • 부정 프롬프트: 생성된 이미지에서 제외할 항목을 설명합니다.

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

    7. send 생성을 클릭합니다.

    Python

    설치

    pip install --upgrade google-genai

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

    Vertex AI에서 생성형 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

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

    • 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의 객체 삭제 기능 제한사항을 설명합니다.

    수정된 픽셀

    모델은 자체 해상도(예: 1024x1024)로 픽셀을 생성하며, 이는 입력 이미지의 해상도와 다를 수 있습니다. 즉, 생성된 이미지에 원본 이미지에 없던 약간의 변경사항이 있을 수 있습니다.

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

    제한사항 삽입

    삽입된 객체는 일반적으로 기본 이미지의 스타일과 일치하지만 일부 키워드는 실사형 출력 대신 만화 같은 결과를 생성할 수 있습니다.

    예를 들어 '노란색 기린'을 요청하면 기린은 원래 갈색과 황갈색이므로 만화 같은 이미지가 생성될 수 있습니다. 부자연스러운 색상의 실사형 이미지를 생성하기는 어려울 수 있습니다.

    다음 단계

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