Amazon Nova Micro is a text-only model with the lowest latency and cost.
Key takeaways:
Nova Canvas allows users to generate high-quality images.
You can guide the AI with detailed text prompts to create images, offering flexibility for various creative projects.
Anyone can generate professional-quality images by describing the scene in text, but well-crafted prompts produce better results.
Nova Canvas supports modifying parts of an image (inpainting) or expanding it (outpainting) for enhanced customization.
Imagine you have an idea for an illustration, but you lack the resources or the time to create it from scratch. With Nova Canvas, you can simply describe the scene, and the AI will bring it to life—giving you the perfect image in seconds. Whether you're looking to generate stunning visuals for social media, websites, or digital marketing, this tool can help. In this Answer, let’s explore how to use Amazon Nova Canvas to generate images efficiently and effectively.
Amazon Nova Canvas brings together the latest advancements in generative AI and image synthesis to help users create high-quality visuals based on text inputs. Here’s why you should consider using Nova Canvas:
Efficient and scalable: Nova Canvas can generate images in seconds, offering great scalability for businesses and developers who need to create large volumes of images.
Creative flexibility: We can guide the AI with detailed prompts to generate exactly the image you need, offering flexibility for various creative projects.
No design skills required: Even if someone is not a designer, Nova Canvas lets create images that look professionally designed by simply providing text prompts.
Inpainting and outpainting: Apart from generating new images, Nova Canvas allows us to modify parts of an image (inpainting) or expand it beyond its original borders (outpainting), providing extra control over our designs.
Before we get started, ensure that you have an AWS account. We need to use Amazon Bedrock, which provides access to Nova Canvas.
Want to learn more about Amazon Bedrock, check out our detailed cloud lab on Building Generative AI Workflows with Amazon Bedrock.
Go to the AWS Management Console and sign in with your AWS account.
In the AWS Management Console, search for "Amazon Bedrock" using the search bar.
Make sure you're in the U.S. East (N. Virginia) (us-east-1) region. If not, change the region by selecting the region name at the top right of the console and choosing U.S. East (N. Virginia) (us-east-1).
In the "Amazon Bedrock console," go to the "Model access" section in the left navigation pane under "Bedrock configurations."
Choose "Enable specific models" under "What is Model access."
From the base models list, select "Nova Canvas."
Select "Next", review your selection, and click "Submit."
After submitting, your access request will be processed. Refresh the "Base models" table to check the status. Once access is granted, the model's status will be listed as "Access granted."
Once access is granted, you can use the Amazon Nova Canvas model for your text and image generation tasks through the console.
We need to install boto3
for AWS interactions, Pillow
for image handling, and botocore
(a dependency of boto3) to manage API calls to AWS services.
pip install boto3 Pillow botocore
You must provide your AWS credentials to access Amazon Bedrock's Nova Canvas model. Make sure you have:
AWS Access Key ID
AWS Secret Access Key
The appropriate AWS region (e.g., us-east-1
)
Here’s an example of how you can generate an image from a text prompt:
The necessary libraries are imported, including boto3
for AWS SDK, PIL
for image handling, and json
for JSON manipulation.
import base64import ioimport jsonimport loggingimport boto3from PIL import Imagefrom botocore.config import Configfrom botocore.exceptions import ClientError
create_image
functionThis function generates an image by sending a request to the Amazon Nova Canvas model through AWS Bedrock's API and returning the image in bytes.
def create_image(model_reference, request_data):# Generates an image using the specified AI model.# Log the start of the image generation processlog_handler.info("Generating image using model %s", model_reference)# Initialize the Amazon Bedrock client for model inferencebedrock_client = boto3.client("bedrock-runtime",region_name=region_name, # AWS regionaws_access_key_id=aws_key_id, # AWS access keyaws_secret_access_key=secret_access_key, # AWS secret keyconfig=Config(read_timeout=300) # Set timeout configuration)# Invoke the model with the request dataresponse = bedrock_client.invoke_model(body=request_data,modelId=model_reference,accept="application/json",contentType="application/json")# Parse the JSON response from the modelresponse_content = json.loads(response.get("body").read())# Extract the generated image encoded in Base64encoded_image = response_content.get("images")[0]# Decode the Base64 string into raw image bytesdecoded_image = base64.b64decode(encoded_image.encode('ascii'))# Check if the response contains an error messageerror_details = response_content.get("error")if error_details is not None:raise CustomImageException(f"Image processing error: {error_details}")# Log successful image generationlog_handler.info("Image successfully generated using model %s", model_reference)return decoded_image
run_process
functionThis function handles setting up the prompt for image generation and calling the create_image
function. The resulting image is saved and displayed using the PIL
library.
def run_process():# Set up logging configuration to display INFO level messages with a specific formatlogging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")# Define the AI model to be used for image generationmodel_reference = 'amazon.nova-canvas-v1:0'# Define the text prompt describing the image to be generatedimage_prompt = """A photograph of red apple on a wooden table.."""# Prepare the request payload with task type, text input, and image configurationrequest_data = json.dumps({"taskType": "TEXT_IMAGE", # Specifies that this is a text-to-image generation task"textToImageParams": {"text": image_prompt # Text prompt describing the desired image},"imageGenerationConfig": {"numberOfImages": 1, # Number of images to generate"height": 1024, # Image height in pixels"width": 1024, # Image width in pixels"cfgScale": 8.0, # Controls creativity and realism of the generated image"seed": 0 # Seed value for reproducibility of results}})try:# Call function to generate the image using the AI modeloutput_image = create_image(model_reference=model_reference, request_data=request_data)# Convert the generated image bytes into a PIL image objectimage_obj = Image.open(io.BytesIO(output_image))# Save the generated image as a PNG file in the output directoryimage_obj.save('output/generated_image.png')# Display the generated image using the default image viewerimage_obj.show()except ClientError as error:# Handle client-related errors such as AWS service failureserror_msg = error.response["Error"]["Message"]log_handler.error("Client error occurred: %s", error_msg)print(f"Client error: {error_msg}")except CustomImageException as error:# Handle errors related to image generation failureslog_handler.error(error.error_msg)print(error.error_msg)else:# Print success message if the image is generated without issuesprint(f"Image successfully generated using model {model_reference}.")
Now we can run the script to generate and display the image. When executed successfully, it will:
Use the Nova Canvas model to generate an image based on the prompt.
Save the generated image as output/graph.png
in your directory.
Open the image using the PIL.Image
viewer.
Please make sure to replace the region_name
, aws_key_id
, and secret_access_key
with your own credentials, and customize the prompt to generate the image of your choice.
import base64import ioimport jsonimport loggingimport boto3from PIL import Imagefrom botocore.config import Configfrom botocore.exceptions import ClientErrorclass CustomImageException(Exception):def __init__(self, error_msg):self.error_msg = error_msglog_handler = logging.getLogger(__name__)logging.basicConfig(level=logging.INFO)def create_image(model_reference, request_data):log_handler.info("Generating image using model %s", model_reference)bedrock_client = boto3.client("bedrock-runtime",region_name=region_name,aws_access_key_id=aws_key_id,aws_secret_access_key=secret_access_key,config=Config(read_timeout=300))response = bedrock_client.invoke_model(body=request_data,modelId=model_reference,accept="application/json",contentType="application/json")response_content = json.loads(response.get("body").read())encoded_image = response_content.get("images")[0]decoded_image = base64.b64decode(encoded_image.encode('ascii'))error_details = response_content.get("error")if error_details is not None:raise CustomImageException(f"Image processing error: {error_details}")log_handler.info("Image successfully generated using model %s", model_reference)return decoded_imagedef run_process():logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")model_reference = 'amazon.nova-canvas-v1:0'image_prompt = """A photograph of red apple on a wooden table.."""request_data = json.dumps({"taskType": "TEXT_IMAGE","textToImageParams": {"text": image_prompt},"imageGenerationConfig": {"numberOfImages": 1,"height": 1024,"width": 1024,"cfgScale": 8.0,"seed": 0}})try:output_image = create_image(model_reference=model_reference, request_data=request_data)image_obj = Image.open(io.BytesIO(output_image))image_obj.save('output/generated_image.png')image_obj.show()except ClientError as error:error_msg = error.response["Error"]["Message"]log_handler.error("Client error occurred: %s", error_msg)print(f"Client error: {error_msg}")except CustomImageException as error:log_handler.error(error.error_msg)print(error.error_msg)else:print(f"Image successfully generated using model {model_reference}.")if __name__ == "__main__":run_process()
Amazon Nova Canvas is a powerful tool for generating high-quality images based on text prompts. This step-by-step guide will help you get started with generating images using the Amazon Nova Canvas model in AWS. Just be sure to replace the region_name
, aws_key_id
, and secret_access_key
with your own credentials, and customize the prompt to generate the image of your choice.
Haven’t found what you were looking for? Contact Us
Free Resources