How to generate images with Amazon Nova Canvas model

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.

Why Amazon Nova Canvas?

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.

How to generate AI images with AWS

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.

1. Set up an AWS account

  • 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).

2. Request access to Amazon Nova Canvas

  • 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.

3. Install required libraries

  • 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

4. Set up AWS credentials

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)

5. Code to generate images using Nova Canvas

Here’s an example of how you can generate an image from a text prompt:

Step 1: Imports and logger setup

The necessary libraries are imported, including boto3 for AWS SDK, PIL for image handling, and json for JSON manipulation.

import base64
import io
import json
import logging
import boto3
from PIL import Image
from botocore.config import Config
from botocore.exceptions import ClientError
Importing necessary libraries

Step 2: Define create_image function

This 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 process
log_handler.info("Generating image using model %s", model_reference)
# Initialize the Amazon Bedrock client for model inference
bedrock_client = boto3.client(
"bedrock-runtime",
region_name=region_name, # AWS region
aws_access_key_id=aws_key_id, # AWS access key
aws_secret_access_key=secret_access_key, # AWS secret key
config=Config(read_timeout=300) # Set timeout configuration
)
# Invoke the model with the request data
response = bedrock_client.invoke_model(
body=request_data,
modelId=model_reference,
accept="application/json",
contentType="application/json"
)
# Parse the JSON response from the model
response_content = json.loads(response.get("body").read())
# Extract the generated image encoded in Base64
encoded_image = response_content.get("images")[0]
# Decode the Base64 string into raw image bytes
decoded_image = base64.b64decode(encoded_image.encode('ascii'))
# Check if the response contains an error message
error_details = response_content.get("error")
if error_details is not None:
raise CustomImageException(f"Image processing error: {error_details}")
# Log successful image generation
log_handler.info("Image successfully generated using model %s", model_reference)
return decoded_image
Defining a create_image function which returns image in bytes

Step 3: Define the run_process function

This 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 format
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
# Define the AI model to be used for image generation
model_reference = 'amazon.nova-canvas-v1:0'
# Define the text prompt describing the image to be generated
image_prompt = """A photograph of red apple on a wooden table.."""
# Prepare the request payload with task type, text input, and image configuration
request_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 model
output_image = create_image(model_reference=model_reference, request_data=request_data)
# Convert the generated image bytes into a PIL image object
image_obj = Image.open(io.BytesIO(output_image))
# Save the generated image as a PNG file in the output directory
image_obj.save('output/generated_image.png')
# Display the generated image using the default image viewer
image_obj.show()
except ClientError as error:
# Handle client-related errors such as AWS service failures
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:
# Handle errors related to image generation failures
log_handler.error(error.error_msg)
print(error.error_msg)
else:
# Print success message if the image is generated without issues
print(f"Image successfully generated using model {model_reference}.")
Defining a run_process function to call create_image function

6. Running the code

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 base64
import io
import json
import logging
import boto3
from PIL import Image
from botocore.config import Config
from botocore.exceptions import ClientError
class CustomImageException(Exception):
def __init__(self, error_msg):
self.error_msg = error_msg
log_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_image
def 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()

Conclusion

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.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Which Amazon Nova Understanding model has the lowest latency and cost?

Amazon Nova Micro is a text-only model with the lowest latency and cost.


What is a recommended best practice for prompting Amazon Nova Canvas?

When prompting image generation models, treat the prompt like an image caption, focusing on details such as subject, action, and environment. Avoid negation words, and refine your prompt iteratively with a consistent seed value to improve results and generate variations.


What is the AWS equivalent of ChatGPT?

Amazon Q is the AWS equivalent of ChatGPT, a generative AI assistant designed to accelerate software development and leverage internal company data.


What are the Amazon Nova models?

Amazon Nova includes models such as understanding models and creative content generation models, which offer capabilities for image generation, text analysis, and other AI tasks.


What is the difference between Amazon Nova and Midjourney?

Amazon Nova is a suite of multimodal AI models (text, images, video) integrated with Amazon Bedrock for enterprise use, focusing on cost-efficiency and real-time applications, while Midjourney is a standalone AI image generation tool, renowned for high-quality, creative visuals, primarily accessed via Discord.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved