아웃페인팅을 사용하여 이미지 콘텐츠 확장

이 페이지에서는 아웃페인팅에 대해 설명합니다. 아웃페인팅을 사용하면 Imagen을 통해 이미지 콘텐츠를 더 큰 영역이나 다른 크기의 영역으로 확장할 수 있습니다.

아웃페인팅 예시

아웃페인팅은 기본 이미지 콘텐츠를 더 크거나 크기가 다른 마스크 캔버스에 맞게 확장할 수 있는 마스크 기반 수정 방법입니다.

샘플 기본 이미지
마스크 이미지(타겟) 크기와 일치하도록 이미지 패딩이 있는 원본 이미지.
이미지 출처: Unsplash카리 셰어
샘플 마스크 이미지
원본 이미지 픽셀 크기와 위치를 표시하여 타겟 출력 크기를 이미지에 마스킹합니다.
샘플 출력 이미지
아웃페인팅 출력 이미지(프롬프트 없음)

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

    자바

    로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 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 설정을 참조하세요.

    Node.js

    로컬 개발 환경에서 이 페이지의 Node.js 샘플을 사용하려면 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 설정을 참조하세요.

    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

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

    콘솔

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

      Media Studio로 이동

    2. 업로드를 클릭합니다. 표시된 파일 대화상자에서 업로드할 파일을 선택합니다.
    3. 아웃페인트를 클릭합니다.
    4. 아웃페인트 메뉴에서 사전 정의된 최종 이미지 가로세로 비율 중 하나를 선택하거나 커스텀을 클릭하여 최종 이미지의 커스텀 측정기준을 정의합니다.
    5. 편집 툴바에서 이미지의 위치를 선택합니다.
      • 왼쪽 정렬:
      • 가로 중앙 정렬:
      • 오른쪽 정렬:
      • 상단 정렬:
      • 세로 중앙 정렬:
      • 하단 정렬:
    6. 선택사항: 파라미터 패널에서 다음 옵션을 조정합니다.
      • 모델: 사용할 Imagen 모델
      • 결과 수: 생성할 결과 수
      • 부정 프롬프트: 생성하지 말아야 할 항목
    7. 프롬프트 필드에 프롬프트를 입력하여 이미지를 수정합니다.
    8. 생성을 클릭합니다.

    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/living_room.png"),
        reference_id=0,
    )
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=Image.from_file(location="test_resources/living_room_mask.png"),
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_USER_PROVIDED",
            mask_dilation=0.03,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A chandelier hanging from the ceiling",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_OUTPAINT",
        ),
    )
    
    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 위치를 참조하세요.
    • prompt: 이미지 아웃페인팅의 경우 빈 문자열을 제공하여 수정된 이미지를 만들 수 있습니다. 프롬프트를 제공하도록 선택한 경우 최상의 결과를 얻으려면 마스크 처리된 영역의 설명을 사용하세요. 예를 들어 '파란 하늘 삽입' 대신 '파란 하늘'을 사용합니다.
    • referenceType: ReferenceImage는 이미지 수정을 위한 추가 컨텍스트를 제공하는 이미지입니다. 사용 사례 수정에는 일반 RGB 원시 참고 이미지(REFERENCE_TYPE_RAW)가 필요합니다. 한 요청에 최대 1개의 원시 참고 이미지가 있을 수 있습니다. 출력 이미지의 높이와 너비는 원시 참고 이미지와 같습니다. 마스크 수정 사용 사례에는 마스크 참고 이미지(REFERENCE_TYPE_MASK)가 필요합니다. 원시 참고 이미지가 있는 경우 마스크 이미지는 원시 참고 이미지와 높이와 너비가 같아야 합니다. 마스크 참고 이미지가 비어 있고 maskModeMASK_MODE_USER_PROVIDED로 설정되지 않은 경우 마스크는 원시 참고 이미지를 토대로 계산됩니다.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • B64_OUTPAINTING_MASK: 원본 이미지를 수정하기 위해 마스크 레이어로 사용할 흑백 이미지. 마스크 해상도는 입력 이미지 해상도와 같아야 합니다. 출력 이미지 해상도는 입력 이미지 해상도와 같습니다. 이 마스크 이미지는 base64로 인코딩된 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB
    • MASK_DILATION - 부동 소수점 수. 이 마스크를 확장할 이미지 너비의 비율입니다. 아웃페인팅에는 0.03 값이 권장됩니다. "dilation": 0.0으로 설정하면 확장 지점에 명확한 테두리가 생기거나 흰색 테두리 효과가 발생할 수 있습니다.
    • EDIT_STEPS - 정수. 기본 모델의 샘플링 단계 수입니다. 아웃페인팅의 경우 35 단계에서 시작합니다. 품질이 요구사항을 충족하지 않으면 단계를 늘립니다.
    • 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": "",
          "referenceImages": [
            {
              "referenceType": "REFERENCE_TYPE_RAW",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "B64_BASE_IMAGE"
              }
            },
            {
              "referenceType": "REFERENCE_TYPE_MASK",
              "referenceId": 2,
              "referenceImage": {
                "bytesBase64Encoded": "B64_OUTPAINTING_MASK"
              },
              "maskImageConfig": {
                "maskMode": "MASK_MODE_USER_PROVIDED",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_OUTPAINT",
        "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. 수정 툴바에서 아웃페인트를 클릭합니다.

    5. 사전 정의된 최종 이미지 가로세로 비율 중 하나를 선택하거나 커스텀을 클릭하여 최종 이미지의 맞춤 측정기준을 정의합니다.

    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_file = "mask-image.png"
    # output_file = "output-image.png"
    # prompt = "" # The optional 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="outpainting",
    )
    
    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

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

    • PROJECT_ID: Google Cloud 프로젝트 ID
    • LOCATION: 프로젝트의 리전. 예를 들면 us-central1, europe-west2, asia-northeast3입니다. 사용 가능한 리전 목록은 Vertex AI의 생성형 AI 위치를 참조하세요.
    • prompt: 이미지 아웃페인팅의 경우 빈 문자열을 제공하여 수정된 이미지를 만들 수 있습니다.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • B64_OUTPAINTING_MASK: 원본 이미지를 수정하기 위해 마스크 레이어로 사용할 흑백 이미지. 마스크 해상도는 입력 이미지 해상도와 같아야 합니다. 출력 이미지 해상도는 입력 이미지 해상도와 같습니다. 이 마스크 이미지는 base64로 인코딩된 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB
    • EDIT_IMAGE_COUNT: 수정된 이미지의 수. 기본값: 4

    HTTP 메서드 및 URL:

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

    JSON 요청 본문:

    {
      "instances": [
        {
          "prompt": "",
          "image": {
              "bytesBase64Encoded": "B64_BASE_IMAGE"
          },
          "mask": {
            "image": {
              "bytesBase64Encoded": "B64_OUTPAINTING_MASK"
            }
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "outpainting"
        }
      }
    }
    

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

    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 메서드에 전달됩니다. 이 서비스는 이미지의 수정된 버전을 반환한 다음 로컬에 저장합니다

    
    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 EditImageOutpaintingMaskSample {
    
      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 optional text prompt describing what you want to see inserted.
    
        editImageOutpaintingMask(projectId, location, inputPath, maskPath, prompt);
      }
    
      // Edit an image using a mask file. Outpainting lets you expand the content of a base image to fit
      // a larger or differently sized mask canvas.
      public static PredictResponse editImageOutpaintingMask(
          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", "outpainting"); // [ "editMode", "outpainting" ]
          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 메서드를 호출합니다. 이 서비스는 로컬로 저장되는 이미지를 생성합니다.

    /**
     * TODO(developer): Update these variables before running the sample.
     */
    const projectId = process.env.CAIP_PROJECT_ID;
    const location = 'us-central1';
    const inputFile = 'resources/roller_skaters.png';
    const maskFile = 'resources/roller_skaters_mask.png';
    const prompt = 'city with skyscrapers';
    
    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 editImageOutpaintingMask() {
      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 optional text prompt describing what you want to see inserted
        editMode: 'outpainting',
        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 editImageOutpaintingMask();

    제한사항

    아웃페인팅된 이미지를 원본 이미지의 200% 이상으로 확장하면 모델이 왜곡된 세부정보를 생성할 수 있습니다. 권장사항에 따라 아웃페인팅된 이미지에 알파 블렌딩을 실행하는 후처리 단계를 추가하는 것이 좋습니다.

    다음 코드는 후처리의 예시입니다.

    parameters = {
       "editConfig": {
           "outpaintingConfig": {
             "blendingMode": "alpha-blending",
             "blendingFactor": 0.01,
           },
       },
    }
    
    

    다음 단계

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