Stability.ai Diffusion 1.0 による画像からの画像生成 - Amazon Bedrock

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Stability.ai Diffusion 1.0 による画像からの画像生成

Stability.ai Diffusion 1.0 モデルには、画像から画像を生成する推論呼び出しを実行するための以下の推論パラメータとモデルレスポンスがあります。

リクエストとレスポンス

リクエスト本文は、 InvokeModelまたは へのリクエストの bodyフィールドに渡されますInvokeModelWithResponseStream

詳細については、https://platform.stability.ai/docs/api-reference#tag/v1generation/operation/imageToImage を参照してください。

Request

Stability.ai Diffusion 1.0 モデルには、画像から画像を生成する推論呼び出しの以下の推論パラメータがあります。

{ "text_prompts": [ { "text": string, "weight": float } ], "init_image" : string , "init_image_mode" : string, "image_strength" : float, "cfg_scale": float, "clip_guidance_preset": string, "sampler": string, "samples" : int, "seed": int, "steps": int, "style_preset": string, "extras" : json object }

必須パラメータを以下に示します。

  • text_prompts — (必須) 生成に使用するテキストプロンプトの配列。各要素は、プロンプトとプロンプトのウェイトを含む JSON オブジェクトです。

    • text — モデルに渡すプロンプト。

      最小値 最大値

      0

      2000

    • weight — (オプション) モデルがプロンプトに適用するウェイト。0 未満の値は負のプロンプトを宣言します。負のプロンプトを使用して、特定の概念を避けるようモデルに伝えます。weight のデフォルト値は 1 です。

  • init_image — (必須) 拡散プロセスの初期化に使用する base64 でエンコードされた画像。

オプションのパラメータを以下に示します。

  • init_image_mode — (オプション) init_image の画像が結果にどの程度影響を与えるかを制御するために image_strength または step_schedule_* のどちらを使用するかを決定します。想定される値は、IMAGE_STRENGTH または STEP_SCHEDULE です。デフォルトは IMAGE_STRENGTH です。

  • image_strength — (オプション) init_image のソース画像が拡散処理にどの程度影響を与えるかを決定します。値が 1 に近い場合、ソース画像と非常に似た画像が生成されます。値が 0 に近い場合、ソース画像と非常に異なる画像が生成されます。

  • cfg_scale — (オプション) 最終的な画像でプロンプトをどの程度表現するかを決定します。小さな数値を指定すると、生成結果におけるランダム性が増します。

    デフォルト値 最小値 最大値

    7

    0

    35

  • clip_guidance_preset – (オプション) 列挙型: FAST_BLUE, FAST_GREEN, NONE, SIMPLE, SLOW, SLOWER, SLOWEST

  • sampler — (オプション) 拡散処理に使用するサンプラー。この値を省略すると、モデルは自動的に適切なサンプラーを選択します。

    列挙型: DDIM DDPM, K_DPMPP_2M, K_DPMPP_2S_ANCESTRAL, K_DPM_2, K_DPM_2_ANCESTRAL, K_EULER, K_EULER_ANCESTRAL, K_HEUN K_LMS

  • samples - (オプション) 生成する画像の数。現在、Amazon Bedrock は 1 つの画像の生成をサポートしています。samples の値を指定する場合、値は 1 である必要があります。

    デフォルト値 最小値 最大値

    1

    1

    1

  • seed – (オプション) シードでは初期ノイズ設定を指定します。前回の実行と同じシードと設定を使用して推論を行えば、類似の画像を作成できます。この値を設定しないか、値が 0 の場合、乱数が設定されます。

    デフォルト値 最小値 最大値

    0

    0

    4294967295

  • steps – (オプション) 生成ステップでは、画像をサンプリングする回数を設定します。このステップの回数が大きいほど、より正確な結果が得られます。

    デフォルト値 最小値 最大値

    30

    10

    50

  • style_preset — (オプション) 画像モデルを特定のスタイルに導くスタイルプリセット。このスタイルプリセットのリストは変更される可能性があります。

    列挙型: 3d-model, analog-film, anime, cinematic, comic-book, digital-art, enhance, fantasy-art, isometric, line-art, low-poly, modeling-compound, neon-punk, origami, photographic, pixel-art, tile-texture

  • extras — (オプション) エンジンに渡される追加のパラメータ。注意して使用してください。このようなパラメータは開発中または実験中の機能に使用され、警告なしに変更される可能性があります。

Response

Stability.ai Diffusion 1.0 モデルでは、テキストから画像を生成する推論呼び出しの以下のフィールドを返します。

{ "result": string, "artifacts": [ { "seed": int, "base64": string, "finishReason": string } ] }
  • result – 操作の結果。成功した場合、レスポンスは success です。

  • artifacts – リクエストされた画像ごとに 1 つずつの画像の配列。

    • seed — 画像の生成に使用されたシードの値。

    • base64 — モデルが生成した base64 でエンコードされた画像。

    • finishedReason – 画像生成プロセスの結果。有効な値は次のとおりです。

      • SUCCESS – 画像生成プロセスが成功しました。

      • ERROR – エラーが発生しました。

      • CONTENT_FILTERED — コンテンツフィルターにより画像がフィルタされ、画像がぼやける可能性があります。

コード例

次の例は、Stability.ai Diffusion 1.0 モデルとオンデマンドスループットを使用して推論を実行する方法を示しています。この例では、テキストプロンプトとリファレンスイメージをモデルに送信し、モデルからレスポンスを取得して、最後に画像を表示します。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image from a reference image with SDXL 1.0 (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 SDXL" 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 SDXL 1.0 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 SDXL 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()) print(response_body['result']) base64_image = response_body.get("artifacts")[0].get("base64") base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("artifacts")[0].get("finishReason") if finish_reason == 'ERROR' or finish_reason == 'CONTENT_FILTERED': raise ImageError(f"Image generation error. Error code is {finish_reason}") logger.info("Successfully generated image withvthe SDXL 1.0 model %s", model_id) return image_bytes def main(): """ Entrypoint for SDXL example. """ logging.basicConfig(level = logging.INFO, format = "%(levelname)s: %(message)s") model_id='stability.stable-diffusion-xl-v1' prompt="""A space ship.""" # Read reference image from file and encode as base64 strings. with open("/path/to/image", "rb") as image_file: init_image = base64.b64encode(image_file.read()).decode('utf8') # Create request body. body=json.dumps({ "text_prompts": [ { "text": prompt } ], "init_image": init_image, "style_preset" : "isometric" }) 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 text with SDXL model {model_id}.") if __name__ == "__main__": main()