Expand image content using mask-based outpainting with Imagen

This sample demonstrates how to use the Imagen model for mask-based image editing. Specify a targeted mask area in which to expand the content of a base image to fit a larger or differently sized canvas.

Code sample

Python

Before trying this sample, follow the Python setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Python API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import vertexai
from vertexai.preview.vision_models import Image, ImageGenerationModel

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# input_file = "my-input.png"
# mask_file = "my-mask.png"
# output_file = "my-output.png"
# prompt = "" # The optional text prompt describing what you want to see inserted.

vertexai.init(project=project_id, location="us-central1")

model = ImageGenerationModel.from_pretrained("imagegeneration@006")
base_img = Image.load_from_file(location=input_file)
mask_img = Image.load_from_file(location=mask_file)

images = model.edit_image(
    base_image=base_img,
    mask=mask_img,
    prompt=prompt,
    edit_mode="outpainting",
)

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")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.