텍스트 프롬프트를 사용한 이미지 수정

이 페이지에서는 텍스트 프롬프트만 사용하여 마스크 없이 수정하는 방법을 설명합니다. 마스크 없는 수정을 사용하면 마스크 없이 이미지를 수정할 수 있습니다. 이 수정 방법은 전체 이미지와 관련된 수정이나 수정 위치가 사용 사례에 중요하지 않은 경우에 유용합니다.

마스크 없는(전체 이미지) 수정 예시

텍스트 프롬프트만 사용하여 기본 이미지(생성되거나 업로드됨)를 수정할 수 있습니다. 수정할 영역을 지정할 필요가 없으며 업데이트는 이미지 전체에 적용됩니다(이를 마스크 없는 수정이라고도 함).

마스크 없는 수정을 수행하려면 무엇을 변경해야 하는지를 지시하기보다는 보고 싶은 내용을 설명하는 프롬프트를 사용하세요. 예를 들어 원본 고양이 이미지를 개로 바꾸고 싶다고 가정해보세요. 이때 '고양이를 개로 바꿔주세요'보다는 ''라는 마스크 없는 수정 프롬프트가 더 효과적일 수 있습니다. 비슷하게, '해변에 있는 고양이'라는 프롬프트로 이미지를 생성했다고 가정해보세요. 이 이미지를 바꾸려면 '해변에 있는 개'라는 수정 프롬프트를 사용하면 됩니다.

원본 고양이 이미지와 수정된 개 이미지
원본 이미지(좌): UnsplashCédric VT
수정된 이미지(우): Vertex AI에서 원본 기본 이미지와 라는 프롬프트를 사용하여 Imagen을 사용하여 생성된 이미지

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

    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 사용을 위한 인증을 참조하세요.

    마스크 없는 수정 사용

    다음 샘플을 사용하여 마스크 영역을 사용하지 않고 전체 이미지를 수정합니다.

    콘솔

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

      Media Studio로 이동
    2. 하단 태스크 패널에서 이미지 수정을 클릭합니다.
    3. 이미지 수정 화면으로 이동합니다.

      생성형 이미지 수정

      1. 텍스트 프롬프트를 사용하여 이미지를 생성합니다.
      2. 생성된 이미지를 클릭합니다.
      3. 이미지 수정을 클릭합니다.

      업로드된 이미지 수정

      1. 이미지 업로드를 클릭합니다.
      2. 수정할 로컬 파일을 선택합니다.
    4. 이미지를 수정하는 새 프롬프트를 입력합니다.

    5. 선택사항. 매개변수를 수정합니다.
    6. 생성을 클릭합니다.

      텍스트만 사용한 이미지 샘플 수정
      말차 케이크 프롬프트로 Vertex AI에서 Imagen으로 수정한 이미지의 수정 이미지 뷰. 우측 상단이 원본 이미지. 원본 이미지 출처: UnsplashDavid Holifield( Google Cloud 콘솔에 표시됨)

    Python

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

    이 샘플에서는 load_from_file 메서드를 사용하여 로컬 파일을 수정할 기본 Image로 참조합니다. 기본 이미지를 지정한 후에는 ImageGenerationModeledit_image 메서드를 사용하고 수정된 이미지를 로컬에 저장합니다. 그런 후 노트북에서 show() 메서드를 사용하여 수정된 이미지를 표시할 수 있습니다.

    
    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"
    # output_file = "output-image.png"
    # prompt = "" # The text prompt describing what you want to see.
    
    vertexai.init(project=PROJECT_ID, location="us-central1")
    
    model = ImageGenerationModel.from_pretrained("imagegeneration@002")
    base_img = Image.load_from_file(location=input_file)
    
    images = model.edit_image(
        base_image=base_img,
        prompt=prompt,
        # Optional parameters
        seed=1,
        # Controls the strength of the prompt.
        # -- 0-9 (low strength), 10-20 (medium strength), 21+ (high strength)
        guidance_scale=21,
        number_of_images=1,
    )
    
    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 위치를 참조하세요.
    • TEXT_PROMPT: 모델이 생성하는 이미지를 안내하는 텍스트 프롬프트. 이 필드는 생성 및 수정 모두에서 필요합니다.
    • B64_BASE_IMAGE: 수정하거나 확대할 기본 이미지. 이미지는 base64 인코딩 바이트 문자열로 지정되어야 합니다. 크기 제한: 10MB.
    • EDIT_IMAGE_COUNT: 수정된 이미지의 수. 기본값: 4

    HTTP 메서드 및 URL:

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

    JSON 요청 본문:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "image": {
            "bytesBase64Encoded": "B64_BASE_IMAGE"
          }
        }
      ],
      "parameters": {
        "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/imagegeneration@002: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@002:predict" | Select-Object -Expand Content
    다음은 "sampleCount": 2 요청에 대한 샘플 응답입니다. 응답은 생성된 이미지 바이트를 base64로 인코딩한 두 개의 예측 객체를 반환합니다.
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    다음 단계

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