Perluas konten gambar menggunakan outpainting berbasis mask dengan Imagen

Contoh ini menunjukkan cara menggunakan model Imagen untuk pengeditan gambar berbasis mask. Tentukan area mask yang ditargetkan untuk memperluas konten gambar dasar agar sesuai dengan kanvas yang lebih besar atau berukuran berbeda.

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_outpainting_mask(
    project_id: str,
    location: str,
    input_file: str,
    mask_file: str,
    output_file: str,
    prompt: str,
) -> vertexai.preview.vision_models.ImageGenerationResponse:
    """Edit a local image by expanding the content of a base image 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_file: Local path to the mask file. Image can be in PNG or JPEG format.
      output_file: Local path to the output image file.
      prompt: The optional text prompt describing what you want to see inserted."""

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

    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)

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