понимание изображений
Модели Gemini изначально созданы для мультимодального анализа, что открывает широкий спектр возможностей для обработки изображений и компьютерного зрения, включая, помимо прочего, создание подписей к изображениям, классификацию и ответы на визуальные вопросы, без необходимости обучения специализированных моделей машинного обучения.
В дополнение к своим общим мультимодальным возможностям, модели Gemini обеспечивают повышенную точность для конкретных сценариев использования, таких как обнаружение и сегментация объектов, за счет дополнительного обучения.
Передача изображений Близнецам
В Gemini можно передавать изображения в качестве входных данных несколькими способами:
- Передача изображения по URL : идеально подходит для общедоступных изображений.
- Передача встроенных данных изображения : для данных изображения, закодированных в формате base64.
- Загрузка изображений с помощью File API : рекомендуется для больших файлов или для повторного использования изображений в нескольких запросах.
Передача изображения по URL-адресу
Вы можете загрузить изображение, используя API файлов , и передать его в запросе:
Python
from google import genai
client = genai.Client()
uploaded_file = client.files.upload(file="path/to/organ.jpg")
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "Caption this image."},
{
"type": "image",
"uri": uploaded_file.uri,
"mime_type": uploaded_file.mime_type
}
]
)
print(interaction.steps[-1].content[0].text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const uploadedFile = await client.files.upload({
file: "path/to/organ.jpg",
config: { mime_type: "image/jpeg" }
});
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{type: "text", text: "Caption this image."},
{
type: "image",
uri: uploadedFile.uri,
mime_type: uploadedFile.mimeType
}
]
});
console.log(interaction.steps.at(-1).content[0].text);
ОТДЫХ
# First upload the file using the Files API, then use the URI:
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "Caption this image."},
{
"type": "image",
"uri": "YOUR_FILE_URI",
"mime_type": "image/jpeg"
}
]
}'
Передача встроенных данных изображения
Вы можете предоставлять данные изображения в виде строк, закодированных в формате base64:
Python
import base64
from google import genai
with open('path/to/small-sample.jpg', 'rb') as f:
image_bytes = f.read()
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "Caption this image."},
{
"type": "image",
"data": base64.b64encode(image_bytes).decode('utf-8'),
"mime_type": "image/jpeg"
}
]
)
print(interaction.steps[-1].content[0].text)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const client = new GoogleGenAI({});
const base64ImageFile = fs.readFileSync("path/to/small-sample.jpg", {
encoding: "base64",
});
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{type: "text", text: "Caption this image."},
{
type: "image",
data: base64ImageFile,
mime_type: "image/jpeg"
}
]
});
console.log(interaction.steps.at(-1).content[0].text);
ОТДЫХ
IMG_PATH="/path/to/your/image1.jpg"
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
B64FLAGS="--input"
else
B64FLAGS="-w0"
fi
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "Caption this image."},
{
"type": "image",
"data": "'"$(base64 $B64FLAGS $IMG_PATH)"'",
"mime_type": "image/jpeg"
}
]
}'
Загрузка изображений с помощью File API
Для работы с большими файлами или для возможности многократного использования одного и того же файла изображения используйте API файлов. См. руководство по API файлов .
Python
from google import genai
client = genai.Client()
my_file = client.files.upload(file="path/to/sample.jpg")
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "Caption this image."},
{
"type": "image",
"uri": my_file.uri,
"mime_type": my_file.mime_type
}
]
)
print(interaction.steps[-1].content[0].text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const myfile = await client.files.upload({
file: "path/to/sample.jpg",
config: { mimeType: "image/jpeg" },
});
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{type: "text", text: "Caption this image."},
{
type: "image",
uri: myfile.uri,
mime_type: myfile.mimeType
}
]
});
console.log(interaction.steps.at(-1).content[0].text);
ОТДЫХ
# First upload the file (see Files API guide for details)
# Then use the file URI in the request:
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "Caption this image."},
{
"type": "image",
"uri": "YOUR_FILE_URI",
"mime_type": "image/jpeg"
}
]
}'
Подсказка с несколькими изображениями
В одном запросе можно указать несколько изображений, включив несколько объектов изображений в массив input :
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What is different between these two images?"},
{
"type": "image",
"uri": "https://example.com/image1.jpg",
"mime_type": "image/jpeg"
},
{
"type": "image",
"uri": "https://example.com/image2.jpg",
"mime_type": "image/jpeg"
}
]
)
print(interaction.steps[-1].content[0].text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{type: "text", text: "What is different between these two images?"},
{
type: "image",
uri: "https://example.com/image1.jpg",
mime_type: "image/jpeg"
},
{
type: "image",
uri: "https://example.com/image2.jpg",
mime_type: "image/jpeg"
}
]
});
console.log(interaction.steps.at(-1).content[0].text);
ОТДЫХ
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What is different between these two images?"},
{
"type": "image",
"uri": "https://example.com/image1.jpg",
"mime_type": "image/jpeg"
},
{
"type": "image",
"uri": "https://example.com/image2.jpg",
"mime_type": "image/jpeg"
}
]
}'
Обнаружение объектов
Модели обучаются обнаруживать объекты на изображении и получать координаты их ограничивающих рамок. Эти координаты, относительно размеров изображения, масштабируются в диапазоне [0, 1000]. Вам необходимо уменьшить масштаб этих координат в соответствии с исходным размером изображения.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import List
import json
client = genai.Client()
prompt = "Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000."
class BoundingBox(BaseModel):
box_2d: List[int] = Field(description="The 2D bounding box of the item as [ymin, xmin, ymax, xmax] normalized to 0-1000.")
mask: List[List[int]] = Field(description="The segmentation mask of the item as a polygon of [x,y] coordinates, normalized to 0-1000.")
label: str = Field(description="A descriptive label for the item.")
class BoundingBoxes(BaseModel):
boxes: List[BoundingBox]
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": prompt},
{
"type": "image",
"uri": "https://example.com/image.png",
"mime_type": "image/png"
}
],
response_format={
"type": "text",
"mime_type": "application/json",
"schema": BoundingBoxes.model_json_schema()
}
)
bounding_boxes = BoundingBoxes.model_validate_json(interaction.steps[-1].content[0].text)
print(bounding_boxes)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const client = new GoogleGenAI({});
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.";
const boundingBoxesJsonSchema = {
type: "object",
properties: {
boxes: {
type: "array",
items: {
type: "object",
properties: {
box_2d: { type: "array", items: { type: "integer" }, description: "The 2D bounding box of the item as [ymin, xmin, ymax, xmax] normalized to 0-1000." },
mask: { type: "array", items: { type: "array", items: { type: "integer" } }, description: "The segmentation mask of the item as a polygon of [x,y] coordinates, normalized to 0-1000." },
label: { type: "string", description: "A descriptive label for the item." }
},
required: ["box_2d", "mask", "label"]
}
}
},
required: ["boxes"]
};
const boundingBoxesSchema = z.fromJSONSchema(boundingBoxesJsonSchema);
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{ type: "text", text: prompt },
{
type: "image",
uri: "https://example.com/image.png",
mime_type: "image/png"
}
],
response_format: {
type: 'text',
mime_type: 'application/json',
schema: boundingBoxesJsonSchema
},
});
const result = boundingBoxesSchema.parse(JSON.parse(interaction.steps.at(-1).content[0].text));
console.log(result);
ОТДЫХ
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000."},
{
"type": "image",
"uri": "https://example.com/image.png",
"mime_type": "image/png"
}
],
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"boxes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"box_2d": { "type": "array", "items": { "type": "integer" } },
"mask": { "type": "array", "items": { "type": "array", "items": { "type": "integer" } } },
"label": { "type": "string" }
},
"required": ["box_2d", "mask", "label"]
}
}
},
"required": ["boxes"]
}
}
}'
Больше примеров можно найти в следующих блокнотах из «Gemini Cookbook» :
Сегментация
Начиная с версии Gemini 2.5, модели не только распознают объекты, но и сегментируют их, а также предоставляют маски контуров.
Модель предсказывает список в формате JSON, где каждый элемент представляет собой маску сегментации. Каждый элемент имеет ограничивающий прямоугольник (" box_2d ") в формате [y0, x0, y1, x1] с нормализованными координатами от 0 до 1000, метку (" label "), идентифицирующую объект, и, наконец, маску сегментации внутри ограничивающего прямоугольника в формате PNG, закодированном в base64, представляющем собой карту вероятностей со значениями от 0 до 255.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import List
import json
client = genai.Client()
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.
"""
class BoundingBox(BaseModel):
box_2d: List[int] = Field(description="The 2D bounding box of the item as [ymin, xmin, ymax, xmax] normalized to 0-1000.")
mask: List[List[int]] = Field(description="The segmentation mask of the item as a polygon of [x,y] coordinates, normalized to 0-1000.")
label: str = Field(description="A descriptive label for the item.")
class BoundingBoxes(BaseModel):
boxes: List[BoundingBox]
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": prompt},
{
"type": "image",
"uri": "https://example.com/image.png",
"mime_type": "image/png"
}
],
response_format={
"type": "text",
"mime_type": "application/json",
"schema": BoundingBoxes.model_json_schema()
},
generation_config={
"thinking_level": "minimal" # Minimize thinking for better detection results
}
)
items = BoundingBoxes.model_validate_json(interaction.steps[-1].content[0].text)
print("Segmentation results:", items)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const client = new GoogleGenAI({});
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.
`;
const boundingBoxesJsonSchema = {
type: "object",
properties: {
boxes: {
type: "array",
items: {
type: "object",
properties: {
box_2d: { type: "array", items: { type: "integer" }, description: "The 2D bounding box of the item as [ymin, xmin, ymax, xmax] normalized to 0-1000." },
mask: { type: "array", items: { type: "array", items: { type: "integer" } }, description: "The segmentation mask of the item as a polygon of [x,y] coordinates, normalized to 0-1000." },
label: { type: "string", description: "A descriptive label for the item." }
},
required: ["box_2d", "mask", "label"]
}
}
},
required: ["boxes"]
};
const boundingBoxesSchema = z.fromJSONSchema(boundingBoxesJsonSchema);
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{ type: "text", text: prompt },
{
type: "image",
uri: "https://example.com/image.png",
mime_type: "image/png"
}
],
response_format: {
type: 'text',
mime_type: 'application/json',
schema: boundingBoxesJsonSchema
},
generationConfig: {
thinking_level: "minimal"
}
});
const result = boundingBoxesSchema.parse(JSON.parse(interaction.steps.at(-1).content[0].text));
console.log(result);
ОТДЫХ
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "Give the segmentation masks for the wooden and glass items.\nOutput a JSON list of segmentation masks where each entry contains the 2D\nbounding box in the key \"box_2d\", the segmentation mask in key \"mask\", and\nthe text label in the key \"label\". Use descriptive labels."},
{
"type": "image",
"uri": "https://example.com/image.png",
"mime_type": "image/png"
}
],
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"boxes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"box_2d": { "type": "array", "items": { "type": "integer" } },
"mask": { "type": "array", "items": { "type": "array", "items": { "type": "integer" } } },
"label": { "type": "string" }
},
"required": ["box_2d", "mask", "label"]
}
}
},
"required": ["boxes"]
}
},
"config": {
"thinking_level": "minimal"
}
}'

Поддерживаемые форматы изображений
Gemini поддерживает следующие MIME-типы форматов изображений:
- PNG -
image/png - JPEG -
image/jpeg - WEBP -
image/webp - HEIC -
image/heic - HEIF -
image/heif
Чтобы узнать о других методах ввода файлов, см. руководство по методам ввода файлов .
Возможности
Все версии модели Gemini являются мультимодальными и могут использоваться в широком спектре задач обработки изображений и компьютерного зрения, включая, помимо прочего, создание подписей к изображениям, визуальные вопросы и ответы, классификацию изображений, обнаружение и сегментацию объектов.
Gemini может снизить потребность в использовании специализированных моделей машинного обучения в зависимости от ваших требований к качеству и производительности.
В последних версиях модели специально разработаны алгоритмы для повышения точности выполнения специализированных задач в дополнение к общим возможностям, таким как улучшенное обнаружение и сегментация объектов.
Ограничения и ключевая техническая информация
ограничение на количество файлов
Модели Gemini поддерживают максимум 3600 файлов изображений за один запрос.
Расчет токенов
- 258 токенов, если оба размера <= 384 пикселя. Изображения большего размера разбиваются на фрагменты размером 768x768 пикселей, каждый из которых стоит 258 токенов.
Примерная формула для расчета количества плиток выглядит следующим образом:
- Рассчитайте приблизительный размер единицы урожая:
floor(min(width, height)/ 1,5). - Разделите каждое измерение на размер единицы урожая и перемножьте полученные значения, чтобы получить количество плиток.
Например, для изображения размером 960x540 размер ячейки кадрирования составит 360. Разделив каждое измерение на 360, получим количество ячеек 3 * 2 = 6.
Разрешение СМИ
Gemini 3 обеспечивает детальный контроль над обработкой мультимодального зрения с помощью параметра media_resolution . Параметр media_resolution определяет максимальное количество токенов, выделяемых на каждое входное изображение или видеокадр. Более высокое разрешение улучшает способность модели считывать мелкий текст или идентифицировать мелкие детали, но увеличивает использование токенов и задержку.
Советы и лучшие практики
- Убедитесь, что изображения правильно повернуты.
- Используйте четкие, неразмытые изображения.
- При использовании одного изображения с текстом, разместите текстовую подсказку перед изображением во
inputмассиве.
Что дальше?
В этом руководстве показано, как загружать файлы изображений и создавать текстовые выходные данные на основе изображений. Для получения дополнительной информации см. следующие ресурсы:
- API для работы с файлами : Узнайте больше о загрузке и управлении файлами для использования с Gemini.
- Системные инструкции : Системные инструкции позволяют управлять поведением модели в соответствии с вашими конкретными потребностями и сценариями использования.
- Стратегии запроса файлов : API Gemini поддерживает запрос файлов с использованием текста, изображений, аудио и видеоданных, также известный как мультимодальный запрос.
- Рекомендации по безопасности : Иногда модели генеративного ИИ выдают неожиданные результаты, например, неточные, предвзятые или оскорбительные. Постобработка и оценка человеком необходимы для минимизации риска причинения вреда от таких результатов.