Mendapatkan respons gambar pendek

Contoh ini menunjukkan cara menggunakan model Imagen untuk mengajukan pertanyaan dan mendapatkan jawaban tentang gambar yang disediakan.

Jelajahi lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

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, ImageTextModel

def get_short_form_image_responses(
    project_id: str, location: str, input_file: str, question: str
) -> list:
    """Get short-form responses to a question about a local image.
    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.
      question: The question about the contents of the image."""

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

    model = ImageTextModel.from_pretrained("imagetext@001")
    source_img = Image.load_from_file(location=input_file)

    answers = model.ask_question(
        image=source_img,
        question=question,
        # Optional parameters
        number_of_results=1,
    )

    print(answers)

    return answers

Langkah selanjutnya

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