Remover conteúdo de imagens usando retoques sem máscaras com o Imagen

Este exemplo demonstra como usar o modelo Imagen para edição de imagens sem máscara. O Imagen detecta e cria automaticamente uma área de máscara na qual remover conteúdo da imagem.

Exemplo de código

Python

Antes de testar esse exemplo, siga as instruções de configuração para Python no Guia de início rápido da Vertex AI sobre como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vertex AI para Python.

Para autenticar na Vertex AI, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import argparse

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

def edit_image_inpainting_remove_mask_mode(
    project_id: str,
    location: str,
    input_file: str,
    mask_mode: str,
    output_file: str,
    prompt: str,
) -> vertexai.preview.vision_models.ImageGenerationResponse:
    """Edit a local image by removing an object using a mask.
    Args:
      project_id: Google Cloud project ID, used to initialize Vertex AI.
      location: Google Cloud region, used to initialize Vertex AI.
      input_file: Local path to the input image file. Image can be in PNG or JPEG format.
      mask_mode: Mask generation mode ('background', 'foreground', or 'semantic').
      output_file: Local path to the output image file.
      prompt: The optional text prompt describing what you want to see in the edited image.
    """

    vertexai.init(project=project_id, location=location)

    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",
        # Optional parameters
        # For semantic mask mode, define the segmentation class IDs:
        # segmentation_classes=[7], # a cat
        # See https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/image-generation#segment-ids.
    )

    images[0].save(location=output_file)

    # Optional. View the edited image in a notebook.
    # images[0].show()

    print(f"Created output image using {len(images[0]._image_bytes)} bytes")

    return images

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.