아마존 타이탄 이미지 제너레이터 G1 모델 - Amazon Bedrock

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

아마존 타이탄 이미지 제너레이터 G1 모델

Amazon Titan Image Generator G1 V1 및 Titan Image Generator G1 V2 모델은 모델 추론을 수행할 때 다음과 같은 추론 파라미터와 모델 응답을 지원합니다.

요청 및 응답 형식

Amazon Titan 이미지 생성기 모델을 사용하여 InvokeModel전화를 걸 때는 요청 body 필드를 사용 사례에 맞는 형식으로 바꾸십시오. 모든 작업은 imageGenerationConfig 객체를 공유하지만 각 작업에는 해당 작업과 관련된 파라미터 객체가 포함되어 있습니다. 다음은 지원되는 사용 사례입니다.

taskType 작업 파라미터 필드 작업 유형 정의
TEXT_IMAGE textToImageParams 생성

텍스트 프롬프트를 사용하여 이미지를 생성합니다.

TEXT_IMAGE textToImageParams 생성

(이미지 컨디셔닝-v2만 해당) 컨디셔닝 이미지의 레이아웃과 구성을 따르는 이미지를 생성하려면 텍스트 프롬프트와 함께 추가 입력 컨디셔닝 이미지를 제공하십시오.

INPAINTING inPaintingParams 편집

마스크 내부를 주변 배경과 일치하도록 변경하여 이미지를 수정합니다.

OUTPAINTING outPaintingParams 편집 마스크로 정의된 영역을 매끄럽게 확장하여 이미지를 수정합니다.
IMAGE_VARIATION imageVariationParams 편집 소스 이미지를 변형하여 이미지를 수정합니다.
COLOR_GUIDED_GENERATION (V2 only) colorGuidedGenerationParams 생성 16진수 색상 코드 목록을 텍스트 프롬프트와 함께 제공하여 색상 팔레트를 따르는 이미지를 생성하십시오.
BACKGROUND_REMOVAL (V2 only) backgroundRemovalParams 편집 여러 개체를 식별하고 배경을 제거하여 이미지를 수정하고 투명한 배경의 이미지를 출력합니다.

편집 작업을 수행하려면 입력에 image 필드가 있어야 합니다. 이 필드는 이미지의 픽셀을 정의하는 문자열로 구성됩니다. 각 픽셀은 RGB 채널 3개로 정의되며 각 채널의 범위는 0에서 255까지입니다. 예를 들어, (255 255 0) 은 노란색을 나타냅니다. 이러한 채널은 base64로 인코딩됩니다.

사용하는 이미지는 또는 형식이어야 합니다. JPEG PNG

인페인팅이나 아웃페인팅을 수행하는 경우 수정할 이미지의 일부를 정의하는 한 영역 또는 여러 영역으로 마스크도 정의합니다. 다음 두 가지 방법 중 하나로 마스크를 정의할 수 있습니다.

  • maskPrompt - 이미지에서 마스킹할 부분을 설명하는 텍스트 프롬프트를 작성합니다.

  • maskImage - 입력 이미지의 각 픽셀을 (0 0 0) 또는 (255 255 255)로 표시하여 마스크 영역을 정의하는 base64 인코딩 문자열을 입력합니다.

    • (0 0 0)으로 정의된 픽셀은 마스크 내부의 픽셀입니다.

    • (255 255 255)로 정의된 픽셀은 마스크 외부의 픽셀입니다.

    사진 편집 도구를 사용하여 마스크를 그릴 수 있습니다. 그런 다음 출력 JPEG 또는 PNG 이미지를 base64 인코딩으로 변환하여 이 필드에 입력할 수 있습니다. 그렇지 않으면 모델을 통해 마스크를 유추할 수 있도록 maskPrompt 필드를 대신 사용합니다.

탭을 선택하면 다양한 이미지 생성 사용 사례에 대한 API 요청 본문과 필드에 대한 설명을 볼 수 있습니다.

Text-to-image generation (Request)

이미지를 생성하기 위한 텍스트 프롬프트는 512자 미만이어야 합니다. 해상도는 긴 쪽이 1,408 미만입니다. negativeText (선택 사항) — 이미지에 포함하지 않을 항목 (512자 미만) 을 정의하는 텍스트 프롬프트입니다. 해상도의 전체 목록은 아래 표를 참조하십시오.

{ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "string", "negativeText": "string" }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }

textToImageParams 필드가 아래에 설명되어 있습니다.

  • text(필수) - 이미지를 생성하기 위한 텍스트 프롬프트입니다.

  • negativeText(선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다.

    참고

    negativeText 프롬프트에 부정적인 단어를 사용하지 않습니다. 예를 들어 이미지에 거울을 포함하지 않으려면 negativeText 프롬프트에 mirrors를 입력합니다. no mirrors는 입력하지 않습니다.

Inpainting (Request)

text(선택 사항) - 마스크 내부에서 변경할 내용을 정의하는 텍스트 프롬프트입니다. 이 필드를 포함시키지 않으면 모델이 전체 마스크 영역을 배경으로 바꾸려고 합니다. 512자 미만이어야 합니다. negativeText (선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다. 512자 미만이어야 합니다. 입력 이미지와 입력 마스크의 크기 제한은 이미지의 긴 쪽에서 1,408 미만입니다. 출력 크기는 입력 크기와 동일합니다.

{ "taskType": "INPAINTING", "inPaintingParams": { "image": "base64-encoded string", "text": "string", "negativeText": "string", "maskPrompt": "string", "maskImage": "base64-encoded string", "returnMask": boolean # False by default }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float } }

inPaintingParams 필드가 아래에 설명되어 있습니다. 마스크는 수정하려는 이미지의 일부를 정의합니다.

  • image (필수) — 수정할 PNG 이미지 JPEG 또는 이미지로, 픽셀 시퀀스를 지정하는 문자열 형식으로, 각각 RGB 값으로 정의되고 base64로 인코딩됩니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법의 예시는 코드 예시를 참조하세요.

  • 이를 정의하려면 다음 필드 중 하나(둘 다 아님)를 정의해야 합니다.

    • maskPrompt— 마스크를 정의하는 텍스트 프롬프트입니다.

    • maskImage— 와 크기가 같은 픽셀 시퀀스를 지정하여 마스크를 정의하는 문자열입니다image. 각 픽셀은 (0 0 0) (마스크 내부의 픽셀) 또는 (255 255 255) (마스크 외부의 픽셀) RGB 값으로 바뀝니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법의 예시는 코드 예시를 참조하세요.

  • text(선택 사항) - 마스크 내부에서 변경할 내용을 정의하는 텍스트 프롬프트입니다. 이 필드를 포함시키지 않으면 모델이 전체 마스크 영역을 배경으로 바꾸려고 합니다.

  • negativeText(선택 사항) — 이미지에 포함하지 않을 항목을 정의하는 텍스트 프롬프트입니다.

    참고

    negativeText 프롬프트에 부정적인 단어를 사용하지 않습니다. 예를 들어 이미지에 거울을 포함하지 않으려면 negativeText 프롬프트에 mirrors를 입력합니다. no mirrors는 입력하지 않습니다.

Outpainting (Request)

text(필수) - 마스크 외부에서 변경할 내용을 정의하는 텍스트 프롬프트입니다. 512자 미만이어야 합니다. negativeText (선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다. 512자 미만이어야 합니다. 입력 이미지와 입력 마스크의 크기 제한은 이미지의 긴 쪽에서 1,408 미만입니다. 출력 크기는 입력 크기와 동일합니다.

{ "taskType": "OUTPAINTING", "outPaintingParams": { "text": "string", "negativeText": "string", "image": "base64-encoded string", "maskPrompt": "string", "maskImage": "base64-encoded string", "returnMask": boolean, # False by default "outPaintingMode": "DEFAULT | PRECISE" }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float } }

outPaintingParams 필드가 아래에 설명되어 있습니다. 마스크는 수정하지 않으려는 이미지의 영역을 정의합니다. 생성 과정에서 정의한 영역이 매끄럽게 확장됩니다.

  • image (필수) — 수정할 PNG 이미지 JPEG 또는 이미지로, 픽셀 시퀀스를 지정하는 문자열 형식으로, 각각 RGB 값으로 정의되고 base64로 인코딩됩니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법의 예시는 코드 예시를 참조하세요.

  • 이를 정의하려면 다음 필드 중 하나(둘 다 아님)를 정의해야 합니다.

    • maskPrompt— 마스크를 정의하는 텍스트 프롬프트입니다.

    • maskImage— 와 크기가 같은 픽셀 시퀀스를 지정하여 마스크를 정의하는 문자열입니다image. 각 픽셀은 (0 0 0) (마스크 내부의 픽셀) 또는 (255 255 255) (마스크 외부의 픽셀) RGB 값으로 바뀝니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법의 예시는 코드 예시를 참조하세요.

  • text(필수) - 마스크 외부에서 변경할 내용을 정의하는 텍스트 프롬프트입니다.

  • negativeText(선택 사항) — 이미지에 포함하지 않을 항목을 정의하는 텍스트 프롬프트입니다.

    참고

    negativeText 프롬프트에 부정적인 단어를 사용하지 않습니다. 예를 들어 이미지에 거울을 포함하지 않으려면 negativeText 프롬프트에 mirrors를 입력합니다. no mirrors는 입력하지 않습니다.

  • outPaintingMode— 마스크 내부의 픽셀 수정을 허용할지 여부를 지정합니다. 다음과 같은 값이 가능합니다.

    • DEFAULT— 이 옵션을 사용하면 재구성된 배경과 일관성을 유지하기 위해 마스크 내부의 이미지를 수정할 수 있습니다.

    • PRECISE— 이 옵션을 사용하면 마스크 내부의 이미지가 수정되지 않도록 할 수 있습니다.

Image variation (Request)

이미지 변형을 사용하면 매개변수 값을 기반으로 원본 이미지의 변형을 만들 수 있습니다. 입력 이미지의 크기 제한은 이미지의 긴 쪽에서 1,408 미만입니다. 전체 해상도 목록은 아래 표를 참조하십시오.

  • text(선택 사항) - 이미지에서 보존할 내용과 변경할 내용을 정의할 수 있는 텍스트 프롬프트입니다. 512자 미만이어야 합니다.

  • negativeText (선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다. 512자 미만이어야 합니다.

  • text(선택 사항) - 이미지에서 보존할 내용과 변경할 내용을 정의할 수 있는 텍스트 프롬프트입니다. 512자 미만이어야 합니다.

  • similarityStrength (선택 사항) — 생성된 이미지가 입력 이미지와 얼마나 유사해야 하는지를 지정합니다. 생성 과정에서 더 많은 임의성을 적용하려면 낮은 값을 사용합니다. 허용 범위는 0.2에서 1.0 (둘 다 포함) 사이이며, 요청에서 이 매개변수가 누락된 경우 기본값인 0.7이 사용됩니다.

{ "taskType": "IMAGE_VARIATION", "imageVariationParams": { "text": "string", "negativeText": "string", "images": ["base64-encoded string"], "similarityStrength": 0.7, # Range: 0.2 to 1.0 }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float } }

imageVariationParams 필드가 아래에 설명되어 있습니다.

  • images(필수) - 변형을 생성할 이미지 목록입니다. 1~5개의 이미지를 포함할 수 있습니다. 이미지는 base64로 인코딩된 이미지 문자열로 정의됩니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법의 예시는 코드 예시를 참조하세요.

  • text(선택 사항) - 이미지에서 보존할 내용과 변경할 내용을 정의할 수 있는 텍스트 프롬프트입니다.

  • similarityStrength(선택 사항) — 생성된 이미지가 입력 이미지와 얼마나 유사해야 하는지를 지정합니다. 범위는 0.2~1.0이며 값이 낮을수록 임의성이 높아집니다.

  • negativeText(선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다.

    참고

    negativeText 프롬프트에 부정적인 단어를 사용하지 않습니다. 예를 들어 이미지에 거울을 포함하지 않으려면 negativeText 프롬프트에 mirrors를 입력합니다. no mirrors는 입력하지 않습니다.

Conditioned Image Generation (Request) V2 only

조건부 이미지 생성 작업 유형을 통해 고객은 생성된 이미지를 보다 세밀하게 제어할 수 있는 “조건 이미지”를 제공하여 text-to-image 생성 범위를 확대할 수 있습니다.

  • 캐니 에지 디텍션

  • 세그멘테이션 맵

이미지를 생성하기 위한 텍스트 프롬프트는 512자 미만이어야 합니다. 해상도는 긴 쪽이 1,408 미만입니다. negativeText (선택 사항) 은 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트이며 512자 미만입니다. 해상도의 전체 목록은 아래 표를 참조하십시오.

{ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "string", "negativeText": "string", "conditionImage": "base64-encoded string", # [OPTIONAL] base64 encoded image "controlMode": "string", # [OPTIONAL] CANNY_EDGE | SEGMENTATION. DEFAULT: CANNY_EDGE "controlStrength": float # [OPTIONAL] weight given to the condition image. DEFAULT: 0.7 }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }
  • text(필수) - 이미지를 생성하기 위한 텍스트 프롬프트입니다.

  • negativeText(선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다.

    참고

    negativeText 프롬프트에 부정적인 단어를 사용하지 않습니다. 예를 들어 이미지에 거울을 포함하지 않으려면 negativeText 프롬프트에 mirrors를 입력합니다. no mirrors는 입력하지 않습니다.

  • conditionImage(선택 사항-V2만 해당) — 생성된 이미지의 레이아웃과 구성을 안내하는 단일 입력 컨디셔닝 이미지입니다. 이미지는 base64로 인코딩된 이미지 문자열로 정의됩니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법에 대한 예제를 제공합니다.

  • controlMode(선택 사항-V2만 해당) — 사용해야 하는 컨디셔닝 모드 유형을 지정합니다. 두 가지 유형의 컨디셔닝 모드가 지원됩니다: CANNY _ 및. EDGE SEGMENTATION 기본값은 CANNY _입니다EDGE.

  • controlStrength(선택 사항-V2만 해당) — 생성된 이미지의 레이아웃 및 구성이 과 얼마나 유사해야 하는지를 지정합니다. conditioningImage 범위는 0에서 1.0까지이며 값이 낮을수록 임의성이 높아집니다. 기본값은 0.7입니다.

참고

controlMode 또는 를 제공하는 경우 controlStrength 이 값도 conditionImage 입력해야 합니다.

Color Guided Content (Request) V2 only

16진수 색상 코드 목록을 텍스트 프롬프트와 함께 제공하여 색상 팔레트를 따르는 이미지를 생성하십시오. 이미지를 생성하려면 텍스트 프롬프트가 512자 미만이어야 합니다. 긴 쪽의 최대 해상도는 1,408입니다. 생성된 이미지의 색상을 지정하려면 1~10개의 16진수 색상 코드 목록이 필요하고, negativeText 선택 사항 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트 (512자 미만), referenceImage 선택 사항 생성 이미지의 색상 팔레트를 안내하는 추가 참조 이미지. 사용자가 업로드한 RGB 참조 이미지의 크기 제한은 긴 쪽이 1,408 미만입니다.

{ "taskType": "COLOR_GUIDED_GENERATION", "colorGuidedGenerationParams": { "text": "string", "negativeText": "string", "referenceImage" "base64-encoded string", # [OPTIONAL] "colors": ["string"] # list of color hex codes }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }

colorGuidedGenerationParams 필드에 대한 설명은 다음과 같습니다. 이 매개변수는 V2에만 해당된다는 점에 유의하십시오.

  • text(필수) - 이미지를 생성하기 위한 텍스트 프롬프트입니다.

  • colors (필수) — 생성된 이미지의 색상을 지정하기 위한 최대 10개의 16진수 색상 코드 목록입니다.

  • negativeText(선택 사항) — 이미지에 포함하지 않을 내용을 정의하는 텍스트 프롬프트입니다.

    참고

    negativeText 프롬프트에 부정적인 단어를 사용하지 않습니다. 예를 들어 이미지에 거울을 포함하지 않으려면 negativeText 프롬프트에 mirrors를 입력합니다. no mirrors는 입력하지 않습니다.

  • referenceImage(선택 사항) — 생성된 이미지의 색상 팔레트를 안내하는 단일 입력 참조 이미지입니다. 이미지는 base64로 인코딩된 이미지 문자열로 정의됩니다.

Background Removal (Request)

배경 제거 작업 유형은 입력 이미지에서 여러 객체를 자동으로 식별하고 배경을 제거합니다. 출력 이미지의 배경은 투명합니다.

요청 형식

{ "taskType": "BACKGROUND_REMOVAL", "backgroundRemovalParams": { "image": "base64-encoded string" } }

응답 형식

{ "images": [ "base64-encoded string", ... ], "error": "string" }

backgroundRemovalParams 필드에 대한 설명은 다음과 같습니다.

  • image (필수) — 수정할 PNG 이미지 JPEG 또는 이미지로, 픽셀 시퀀스를 지정하는 문자열 형식으로, 각 픽셀은 RGB 값으로 정의되고 base64로 인코딩됩니다.

Response body
{ "images": [ "base64-encoded string", ... ], "error": "string" }

응답 본문은 다음 필드 중 하나를 포함하는 스트리밍 객체입니다.

  • images - 요청이 성공하면 각각 생성된 이미지를 정의하는 base64로 인코딩된 문자열 목록인 이 필드가 반환됩니다. 각 이미지는 픽셀 시퀀스를 지정하는 문자열로 포맷되며, 각 픽셀은 RGB 값으로 정의되고 base64로 인코딩됩니다. 이미지를 base64로 인코딩하고 base64로 인코딩된 문자열을 디코딩하여 이미지로 변환하는 방법의 예시는 코드 예시를 참조하세요.

  • error - 요청이 다음 상황 중 하나에서 콘텐츠 조절 정책을 위반하는 경우 이 필드에 메시지가 반환됩니다.

    • 입력 텍스트, 이미지 또는 마스크 이미지에 콘텐츠 조절 정책에 의해 플래그가 지정된 경우

    • 콘텐츠 조절 정책에 따라 출력 이미지가 하나 이상 플래그된 경우

공동 및 선택 사항인 imageGenerationConfig는 다음 필드로 구성됩니다. 이 객체를 포함시키지 않으면 기본 구성이 사용됩니다.

  • numberOfImages(선택 사항) — 생성할 이미지 수입니다.

    최소 Maximum 기본값
    1 5 1
  • cfgScale(선택 사항) — 생성된 이미지가 프롬프트를 얼마나 강하게 준수해야 하는지를 지정합니다. 생성 과정에서 더 많은 무작위화를 도입하려면 낮은 값을 사용합니다.

    최소 Maximum 기본값
    1.1 10.0 8.0
  • 다음 파라미터는 원하는 출력 이미지 크기를 정의합니다. 이미지 크기별 요금에 대한 자세한 내용은 Amazon Bedrock 요금을 참조하세요.

    • height(선택 사항) – 이미지의 높이입니다(픽셀). 기본값은 1408입니다.

    • width(선택 사항) – 이미지의 너비입니다(픽셀). 기본값은 1408입니다.

    허용되는 크기는 다음과 같습니다.

    너비 높이 가로 세로 비율 대상과 동일한 가격
    1024 1024 1:1 1024 x 1024
    768 768 1:1 512 x 512
    512 512 1:1 512 x 512
    768 1152 2:3 1024 x 1024
    384 576 2:3 512 x 512
    1152 768 3:00 1024 x 1024
    576 384 3:00 512 x 512
    768 1,280 3:5 1024 x 1024
    384 640 3:5 512 x 512
    1,280 768 5:3 1024 x 1024
    640 384 5:3 512 x 512
    896 1152 7:9 1024 x 1024
    448 576 7:9 512 x 512
    1152 896 9:7 1024 x 1024
    576 448 9:7 512 x 512
    768 1408 6:11 1024 x 1024
    384 704 6:11 512 x 512
    1408 768 11:6 1024 x 1024
    704 384 11:6 512 x 512
    640 1408 5:11 1024 x 1024
    320 704 5:11 512 x 512
    1408 640 11:5 1024 x 1024
    704 320 11:5 512 x 512
    1152 640 9:5 1024 x 1024
    1173 640 16:9 1024 x 1024
  • seed(선택 사항) - 결과를 제어하고 재현하는 데 사용합니다. 초기 노이즈 설정을 결정합니다. 추론을 통해 비슷한 이미지를 만들 수 있도록 하려면 이전 실행과 동일한 시드 및 동일한 설정을 사용합니다.

    최소 Maximum 기본값
    0 2,147,483,646 0

코드 예시

다음 예는 Python에서 온디맨드 처리량으로 Amazon Titan 이미지 생성기 모델을 호출하는 방법을 보여줍니다. SDK 탭을 선택하면 각 사용 사례의 예시를 볼 수 있습니다. 각 예시의 하단에 이미지가 표시됩니다.

Text-to-image generation
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image from a text prompt with the Amazon Titan Image Generator G1 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' prompt = """A photograph of a cup of coffee from the side.""" body = json.dumps({ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": prompt }, "imageGenerationConfig": { "numberOfImages": 1, "height": 1024, "width": 1024, "cfgScale": 8.0, "seed": 0 } }) try: image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Inpainting
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use inpainting to generate an image from a source image with the Amazon Titan Image Generator G1 model (on demand). The example uses a mask prompt to specify the area to inpaint. """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "INPAINTING", "inPaintingParams": { "text": "Modernize the windows of the house", "negativeText": "bad quality, low res", "image": input_image, "maskPrompt": "windows" }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Outpainting
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use outpainting to generate an image from a source image with the Amazon Titan Image Generator G1 model (on demand). The example uses a mask image to outpaint the original image. """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' # Read image and mask image from file and encode as base64 strings. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') with open("/path/to/mask_image", "rb") as mask_image_file: input_mask_image = base64.b64encode( mask_image_file.read()).decode('utf8') body = json.dumps({ "taskType": "OUTPAINTING", "outPaintingParams": { "text": "Draw a chocolate chip cookie", "negativeText": "bad quality, low res", "image": input_image, "maskImage": input_mask_image, "outPaintingMode": "DEFAULT" }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } } ) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Image variation
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image variation from a source image with the Amazon Titan Image Generator G1 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "IMAGE_VARIATION", "imageVariationParams": { "text": "Modernize the house, photo-realistic, 8k, hdr", "negativeText": "bad quality, low resolution, cartoon", "images": [input_image], "similarityStrength": 0.7, # Range: 0.2 to 1.0 }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Image conditioning (V2 only)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate image conditioning from a source image with the Amazon Titan Image Generator G1 V2 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator V2" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator V2 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator V2 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v2:0' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "A robot playing soccer, anime cartoon style", "negativeText": "bad quality, low res", "conditionImage": input_image, "controlMode": "CANNY_EDGE" }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.") if __name__ == "__main__": main()
Color guided content (V2 only)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image from a source image color palette with the Amazon Titan Image Generator G1 V2 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator V2" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator V2 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator V2 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v2:0' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "COLOR_GUIDED_GENERATION", "colorGuidedGenerationParams": { "text": "digital painting of a girl, dreamy and ethereal, pink eyes, peaceful expression, ornate frilly dress, fantasy, intricate, elegant, rainbow bubbles, highly detailed, digital painting, artstation, concept art, smooth, sharp focus, illustration", "negativeText": "bad quality, low res", "referenceImage": input_image, "colors": ["#ff8080", "#ffb280", "#ffe680", "#ffe680"] }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.") if __name__ == "__main__": main()
Background removal (V2 only)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image with background removal with the Amazon Titan Image Generator G1 V2 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator V2" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator V2 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator V2 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v2:0' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "BACKGROUND_REMOVAL", "backgroundRemovalParams": { "image": input_image, } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.") if __name__ == "__main__": main()