Hapus konten gambar menggunakan deteksi mask otomatis dan inpainting dengan Imagen

Contoh ini menunjukkan cara menggunakan model Imagen untuk pengeditan gambar bebas mask. Gambarn otomatis mendeteksi dan membuat area mask untuk menghapus konten gambar.

Contoh kode

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.