Remove image content using automatic mask detection and inpainting with Imagen

This sample demonstrates how to use the Imagen model for mask-free image editing. Imagen automatically detects and creates a mask area in which to remove image content.

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 = "your-project-id"
# input_file = "input-image.png"
# mask_mode = "foreground" # 'background', 'foreground', or 'semantic'
# output_file = "output-image.png"
# prompt = "sports car" # The text prompt describing what you want to see in the edited image.

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

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

images = model.edit_image(
    base_image=base_img,
    mask_mode=mask_mode,
    prompt=prompt,
    edit_mode="inpainting-remove",
)

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")
# Example response:
# Created output image using 1279948 bytes

What's next

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