Pemahaman gambar

Model Gemini dapat memproses gambar, sehingga memungkinkan banyak kasus penggunaan developer rintisan yang secara historis memerlukan model khusus domain. Beberapa kemampuan visi Gemini mencakup kemampuan untuk:

  • Memberi teks dan menjawab pertanyaan tentang gambar
  • Mentranskripsikan dan melakukan penalaran atas PDF, termasuk hingga 2 juta token
  • Mendeteksi objek dalam gambar dan menampilkan koordinat kotak pembatas untuk objek tersebut
  • Menyaring objek dalam gambar

Gemini dirancang untuk bersifat multimodal sejak awal dan kami terus mendorong batas kemampuan yang ada. Panduan ini menunjukkan cara menggunakan Gemini API untuk membuat respons teks berdasarkan input gambar dan melakukan tugas pemahaman gambar umum.

Sebelum memulai

Sebelum memanggil Gemini API, pastikan Anda telah menginstal SDK pilihan, dan kunci Gemini API dikonfigurasi serta siap digunakan.

Input gambar

Anda dapat memberikan gambar sebagai input ke Gemini dengan cara berikut:

  • Upload file gambar menggunakan File API sebelum membuat permintaan ke generateContent. Gunakan metode ini untuk file yang lebih besar dari 20 MB atau saat Anda ingin menggunakan kembali file di beberapa permintaan.
  • Teruskan data gambar inline dengan permintaan ke generateContent. Gunakan metode ini untuk file yang lebih kecil (<20 MB total ukuran permintaan) atau gambar yang diambil langsung dari URL.

Mengupload file gambar

Anda dapat menggunakan Files API untuk mengupload file gambar. Selalu gunakan Files API jika total ukuran permintaan (termasuk file, perintah teks, petunjuk sistem, dll.) lebih besar dari 20 MB, atau jika Anda ingin menggunakan gambar yang sama di beberapa perintah.

Kode berikut mengupload file gambar, lalu menggunakan file dalam panggilan ke generateContent.

Python

from google import genai

client = genai.Client(api_key="GOOGLE_API_KEY")

myfile = client.files.upload(file="path/to/sample.jpg")

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=[myfile, "Caption this image."])

print(response.text)

JavaScript

import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });

async function main() {
  const myfile = await ai.files.upload({
    file: "path/to/sample.jpg",
    config: { mimeType: "image/jpeg" },
  });

  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: createUserContent([
      createPartFromUri(myfile.uri, myfile.mimeType),
      "Caption this image.",
    ]),
  });
  console.log(response.text);
}

await main();

Go

file, err := client.UploadFileFromPath(ctx, "path/to/sample.jpg", nil)
if err != nil {
    log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
    genai.FileData{URI: file.URI},
    genai.Text("Caption this image."))
if err != nil {
    log.Fatal(err)
}

printResponse(resp)

REST

IMAGE_PATH="path/to/sample.jpg"
MIME_TYPE=$(file -b --mime-type "${IMAGE_PATH}")
NUM_BYTES=$(wc -c < "${IMAGE_PATH}")
DISPLAY_NAME=IMAGE

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${IMAGE_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}},
          {"text": "Caption this image."}]
        }]
      }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Untuk mempelajari lebih lanjut cara menggunakan file media, lihat Files API.

Meneruskan data gambar secara inline

Daripada mengupload file gambar, Anda dapat meneruskan data gambar inline dalam permintaan ke generateContent. Hal ini cocok untuk gambar yang lebih kecil (total ukuran permintaan kurang dari 20 MB) atau gambar yang diambil langsung dari URL.

Anda dapat memberikan data gambar sebagai string berenkode Base64 atau dengan membaca file lokal secara langsung (bergantung pada SDK).

File gambar lokal:

Python

  from google.genai import types

  with open('path/to/small-sample.jpg', 'rb') as f:
      img_bytes = f.read()

  response = client.models.generate_content(
    model='gemini-2.0-flash',
    contents=[
      types.Part.from_bytes(
        data=img_bytes,
        mime_type='image/jpeg',
      ),
      'Caption this image.'
    ]
  )

  print(response.text)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const base64ImageFile = fs.readFileSync("path/to/small-sample.jpg", {
  encoding: "base64",
});

const contents = [
  {
    inlineData: {
      mimeType: "image/jpeg",
      data: base64ImageFile,
    },
  },
  { text: "Caption this image." },
];

const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(response.text);

Go

model := client.GenerativeModel("gemini-2.0-flash")

bytes, err := os.ReadFile("path/to/small-sample.jpg")
if err != nil {
  log.Fatal(err)
}

prompt := []genai.Part{
  genai.Blob{MIMEType: "image/jpeg", Data: bytes},
  genai.Text("Caption this image."),
}

resp, err := model.GenerateContent(ctx, prompt...)
if err != nil {
  log.Fatal(err)
}

for _, c := range resp.Candidates {
  if c.Content != nil {
    fmt.Println(*c.Content)
  }
}

REST

IMG_PATH=/path/to/your/image1.jpg

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
            {
              "inline_data": {
                "mime_type":"image/jpeg",
                "data": "'\$(base64 \$B64FLAGS \$IMG_PATH)'"
              }
            },
            {"text": "Caption this image."},
        ]
      }]
    }' 2> /dev/null

Gambar dari URL:

Python

from google import genai
from google.genai import types

import requests

image_path = "https://goo.gle/instrument-img"
image = requests.get(image_path)

client = genai.Client(api_key="GOOGLE_API_KEY")
response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents=["What is this image?",
              types.Part.from_bytes(data=image.content, mime_type="image/jpeg")])

print(response.text)

JavaScript

import { GoogleGenAI } from "@google/genai";

async function main() {
  const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY });

  const imageUrl = "https://goo.gle/instrument-img";

  const response = await fetch(imageUrl);
  const imageArrayBuffer = await response.arrayBuffer();
  const base64ImageData = Buffer.from(imageArrayBuffer).toString('base64');

  const result = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: [
    {
      inlineData: {
        mimeType: 'image/jpeg',
        data: base64ImageData,
      },
    },
    { text: "Caption this image." }
  ],
  });
  console.log(result.text);
}

main();

Go

func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GOOGLE_API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-2.0-flash")

// Download the image.
imageResp, err := http.Get("https://goo.gle/instrument-img")
if err != nil {
  panic(err)
}
defer imageResp.Body.Close()

imageBytes, err := io.ReadAll(imageResp.Body)
if err != nil {
  panic(err)
}

// Create the request.
req := []genai.Part{
  genai.ImageData("jpeg", imageBytes),

  genai.Text("Caption this image."),
}

// Generate content.
resp, err := model.GenerateContent(ctx, req...)
if err != nil {
  panic(err)
}

// Handle the response of generated text.
for _, c := range resp.Candidates {
  if c.Content != nil {
    fmt.Println(*c.Content)
  }
}

}

REST

IMG_URL="https://goo.gle/instrument-img"

MIME_TYPE=$(curl -sIL "$IMG_URL" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\r$//' | head -n 1)
if [[ -z "$MIME_TYPE" || ! "$MIME_TYPE" == image/* ]]; then
  MIME_TYPE="image/jpeg"
fi

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
            {
              "inline_data": {
                "mime_type":"'"$MIME_TYPE"'",
                "data": "'$(curl -sL "$IMG_URL" | base64 $B64FLAGS)'"
              }
            },
            {"text": "Caption this image."}
        ]
      }]
    }' 2> /dev/null

Beberapa hal yang perlu diingat tentang data gambar inline:

  • Ukuran total permintaan maksimum adalah 20 MB, yang mencakup perintah teks, petunjuk sistem, dan semua file yang disediakan secara inline. Jika ukuran file Anda akan membuat total ukuran permintaan melebihi 20 MB, gunakan Files API untuk mengupload file gambar untuk digunakan dalam permintaan.
  • Jika Anda menggunakan sampel gambar beberapa kali, akan lebih efisien untuk mengupload file gambar menggunakan File API.

Perintah dengan beberapa gambar

Anda dapat memberikan beberapa gambar dalam satu perintah dengan menyertakan beberapa objek Part gambar dalam array contents. Ini dapat berupa campuran data inline (file lokal atau URL) dan referensi File API.

Python

from google import genai
from google.genai import types

client = genai.Client(api_key="GOOGLE_API_KEY")

# Upload the first image
image1_path = "path/to/image1.jpg"
uploaded_file = client.files.upload(file=image1_path)

# Prepare the second image as inline data
image2_path = "path/to/image2.png"
with open(image2_path, 'rb') as f:
    img2_bytes = f.read()

# Create the prompt with text and multiple images
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=[
        "What is different between these two images?",
        uploaded_file,  # Use the uploaded file reference
        types.Part.from_bytes(
            data=img2_bytes,
            mime_type='image/png'
        )
    ]
)

print(response.text)

JavaScript

import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });

async function main() {
  // Upload the first image
  const image1_path = "path/to/image1.jpg";
  const uploadedFile = await ai.files.upload({
    file: image1_path,
    config: { mimeType: "image/jpeg" },
  });

  // Prepare the second image as inline data
  const image2_path = "path/to/image2.png";
  const base64Image2File = fs.readFileSync(image2_path, {
    encoding: "base64",
  });

  // Create the prompt with text and multiple images
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: createUserContent([
      "What is different between these two images?",
      createPartFromUri(uploadedFile.uri, uploadedFile.mimeType),
      {
        inlineData: {
          mimeType: "image/png",
          data: base64Image2File,
        },
      },
    ]),
  });
  console.log(response.text);
}

await main();

Go

+    // Upload the first image
image1Path := "path/to/image1.jpg"
uploadedFile, err := client.UploadFileFromPath(ctx, image1Path, nil)
if err != nil {
    log.Fatal(err)
}
defer client.DeleteFile(ctx, uploadedFile.Name)

// Prepare the second image as inline data
image2Path := "path/to/image2.png"
img2Bytes, err := os.ReadFile(image2Path)
if err != nil {
  log.Fatal(err)
}

// Create the prompt with text and multiple images
model := client.GenerativeModel("gemini-2.0-flash")
prompt := []genai.Part{
  genai.Text("What is different between these two images?"),
  genai.FileData{URI: uploadedFile.URI},
  genai.Blob{MIMEType: "image/png", Data: img2Bytes},
}

resp, err := model.GenerateContent(ctx, prompt...)
if err != nil {
  log.Fatal(err)
}

printResponse(resp)

REST

# Upload the first image
IMAGE1_PATH="path/to/image1.jpg"
MIME1_TYPE=$(file -b --mime-type "${IMAGE1_PATH}")
NUM1_BYTES=$(wc -c < "${IMAGE1_PATH}")
DISPLAY_NAME1=IMAGE1

tmp_header_file1=upload-header1.tmp

curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header1.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM1_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME1_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME1}'}}" 2> /dev/null

upload_url1=$(grep -i "x-goog-upload-url: " "${tmp_header_file1}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file1}"

curl "${upload_url1}" \
  -H "Content-Length: ${NUM1_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${IMAGE1_PATH}" 2> /dev/null > file_info1.json

file1_uri=$(jq ".file.uri" file_info1.json)
echo file1_uri=$file1_uri

# Prepare the second image (inline)
IMAGE2_PATH="path/to/image2.png"
MIME2_TYPE=$(file -b --mime-type "${IMAGE2_PATH}")

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi
IMAGE2_BASE64=$(base64 $B64FLAGS $IMAGE2_PATH)

# Now generate content using both images
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "What is different between these two images?"},
          {"file_data":{"mime_type": "'"${MIME1_TYPE}"'", "file_uri": '$file1_uri'}},
          {
            "inline_data": {
              "mime_type":"'"${MIME2_TYPE}"'",
              "data": "'"$IMAGE2_BASE64"'"
            }
          }
        ]
      }]
    }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Mendapatkan kotak pembatas untuk objek

Model Gemini dilatih untuk mengidentifikasi objek dalam gambar dan memberikan koordinat kotak pembatasnya. Koordinat ditampilkan relatif terhadap dimensi gambar, yang diskalakan ke [0, 1000]. Anda perlu menskalakan ulang koordinat ini berdasarkan ukuran gambar asli.

Python

prompt = "Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000."

JavaScript

const prompt = "Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000.";

Go

prompt := []genai.Part{
    genai.FileData{URI: sampleImage.URI},
    genai.Text("Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000."),
}

REST

PROMPT="Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000."

Anda dapat menggunakan kotak pembatas untuk deteksi dan pelokalan objek dalam gambar dan video. Dengan mengidentifikasi dan menandai objek secara akurat dengan kotak batas, Anda dapat membuka berbagai aplikasi dan meningkatkan kecerdasan project Anda.

Manfaat utama

  • Mudah: Integrasikan kemampuan deteksi objek ke dalam aplikasi Anda dengan mudah, apa pun keahlian computer vision Anda.
  • Dapat disesuaikan: Membuat kotak pembatas berdasarkan petunjuk kustom (misalnya, "Saya ingin melihat kotak pembatas semua objek hijau dalam gambar ini"), tanpa harus melatih model kustom.

Detail teknis

  • Input: Perintah Anda dan gambar atau frame video terkait.
  • Output: Bounding box dalam format [y_min, x_min, y_max, x_max]. Sudut kiri atas adalah asal. Sumbu x dan y masing-masing bergerak secara horizontal dan vertikal. Nilai koordinat dinormalisasi menjadi 0-1000 untuk setiap gambar.
  • Visualisasi: Pengguna AI Studio akan melihat kotak pembatas yang diplot dalam UI.

Untuk developer Python, coba notebook pemahaman spasial 2D atau notebook penunjuk 3D eksperimental.

Menormalisasi koordinat

Model menampilkan koordinat kotak pembatas dalam format [y_min, x_min, y_max, x_max]. Untuk mengonversi koordinat ternormalisasi ini ke koordinat piksel gambar asli Anda, ikuti langkah-langkah berikut:

  1. Bagi setiap koordinat output dengan 1.000.
  2. Kalikan koordinat x dengan lebar gambar asli.
  3. Kalikan koordinat y dengan tinggi gambar asli.

Untuk mempelajari contoh yang lebih mendetail tentang cara membuat koordinat kotak pembatas dan memvisualisasikannya pada gambar, tinjau contoh cookbook Deteksi Objek.

Segmentasi gambar

Mulai dari model Gemini 2.5, model Gemini dilatih untuk tidak hanya mendeteksi item, tetapi juga menyegmentasikannya dan memberikan mask kontur.

Model memprediksi daftar JSON, dengan setiap item mewakili mask segmentasi. Setiap item memiliki kotak pembatas ("box_2d") dalam format [y0, x0, y1, x1] dengan koordinat yang dinormalisasi antara 0 dan 1000, label ("label") yang mengidentifikasi objek, dan terakhir mask segmentasi di dalam kotak pembatas, sebagai png yang dienkode base64 yang merupakan peta probabilitas dengan nilai antara 0 dan 255. Topeng perlu diubah ukurannya agar cocok dengan dimensi kotak pembatas, lalu di-binerkan pada nilai minimum keyakinan Anda (127 untuk titik tengah).

Python

prompt = """
  Give the segmentation masks for the wooden and glass items.
  Output a JSON list of segmentation masks where each entry contains the 2D
  bounding box in the key "box_2d", the segmentation mask in key "mask", and
  the text label in the key "label". Use descriptive labels.
"""

JavaScript

const prompt = `
  Give the segmentation masks for the wooden and glass items.
  Output a JSON list of segmentation masks where each entry contains the 2D
  bounding box in the key "box_2d", the segmentation mask in key "mask", and
  the text label in the key "label". Use descriptive labels.
`;    

Go

prompt := []genai.Part{
    genai.FileData{URI: sampleImage.URI},
    genai.Text(`
      Give the segmentation masks for the wooden and glass items.
      Output a JSON list of segmentation masks where each entry contains the 2D
      bounding box in the key "box_2d", the segmentation mask in key "mask", and
      the text label in the key "label". Use descriptive labels.
    `),
}

REST

PROMPT='''
  Give the segmentation masks for the wooden and glass items.
  Output a JSON list of segmentation masks where each entry contains the 2D
  bounding box in the key "box_2d", the segmentation mask in key "mask", and
  the text label in the key "label". Use descriptive labels.
'''
Meja dengan cupcake, dengan objek kayu dan kaca yang ditandai
Mask objek kayu dan kaca yang ditemukan pada gambar

Lihat contoh segmentasi dalam panduan cookbook untuk mengetahui contoh yang lebih mendetail.

Format gambar yang didukung

Gemini mendukung jenis MIME format gambar berikut:

  • PNG - image/png
  • JPEG - image/jpeg
  • WEBP - image/webp
  • HEIC - image/heic
  • HEIF - image/heif

Detail teknis tentang gambar

  • Batas file: Gemini 2.5 Pro, 2.0 Flash, 1.5 Pro, dan 1.5 Flash mendukung maksimum 3.600 file gambar per permintaan.
  • Penghitungan token:
    • Gemini 1.5 Flash dan Gemini 1.5 Pro: 258 token jika kedua dimensinya <= 384 piksel. Gambar yang lebih besar akan disusun bertingkat (ubin minimum 256 piksel, maksimum 768 piksel, diubah ukurannya menjadi 768x768), dengan setiap ubin berharga 258 token.
    • Gemini 2.0 Flash: 258 token jika kedua dimensinya <= 384 piksel. Gambar yang lebih besar akan dipecah menjadi ubin berukuran 768x768 piksel, dengan biaya masing-masing 258 token.
  • Praktik terbaik:
    • Pastikan gambar diputar dengan benar.
    • Gunakan gambar yang jelas dan tidak buram.
    • Saat menggunakan satu gambar dengan teks, tempatkan perintah teks setelah bagian gambar dalam array contents.

Langkah berikutnya

Panduan ini menunjukkan cara mengupload file gambar dan menghasilkan output teks dari input gambar. Untuk mempelajari lebih lanjut, lihat referensi berikut:

  • Petunjuk sistem: Petunjuk sistem memungkinkan Anda mengarahkan perilaku model berdasarkan kebutuhan dan kasus penggunaan tertentu.
  • Pemahaman video: Pelajari cara menggunakan input video.
  • Files API: Pelajari lebih lanjut cara mengupload dan mengelola file untuk digunakan dengan Gemini.
  • Strategi perintah file: Gemini API mendukung perintah dengan data teks, gambar, audio, dan video, yang juga dikenal sebagai perintah multimodal.
  • Panduan keamanan: Terkadang model AI generatif menghasilkan output yang tidak terduga, seperti output yang tidak akurat, bias, atau menyinggung. Pascapemrosesan dan evaluasi manusia sangat penting untuk membatasi risiko bahaya dari output tersebut.