翻篇收录说明
翻篇网页快照

Image understanding with Gemma 4 - Gemma Docs

https://gemma.ai/get-started/capabilities/image/

最近抓取:2026-12-03 11:18:53(北京时间)

最近内容变化:2026-11-30 08:56:49(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Analyze images with Gemma 4 using variable aspect ratios, configurable vision token budgets, and multi-image prompts.

正文摘录

Image understanding¶ Models Gemma 4 Uses Transformers Colab View as markdown You can use Gemma 3 and later models to analyze and understand the content of images. This capability includes tasks like describing image content, identifying objects, recognizing scenes, and even inferring the context from visual information. Here are some examples demonstrating these capabilities. Install Python packages¶ Install the Hugging Face libraries required for running the Gemma model and making requests. # Install PyTorch & other libraries pip install torch accelerate # Install the transformers library pip install "transformers>=5.10.1" Load Model¶ Use transformers library to load the pipeline MODEL_ID = "google/gemma-4-E2B-it" from transformers import pipeline vqa_pipe = pipeline( task="image-text-to-text", model=MODEL_ID, device_map="auto", dtype="auto" ) Use a prompt template¶ The following example shows how to provide an image and ask question about it. from PIL import Image from IPython.display import display import requests from transformers import GenerationConfig config = GenerationConfig.from_pretrained(MODEL_ID) config.max_new_tokens = 512 gen_kwargs = dict(generation_config=config) img_url = "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/apps/sample-data/GoldenGate.png" input_image = Image.open(requests.get(img_url, stream=True).raw) display(input_image) messages = [ { "role": "user", "content": [ {"type": "image", "url": img_url}, {"type": "text", "text": "What is shown in this image?"} ] } ] output = vqa_pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs) print(output[0]['generated_text']) This image shows the **Golden Gate Bridge** in San Francisco, California. Key elements visible in the picture include: * **The Golden Gate Bridge:** The iconic red suspension bridge spanning a body of water. * **The Water:** A large expanse of water (likely the San Francisco Bay or the Pacific Ocean). * **A Rocky Outcrop/Island:** In the foreground, there is a dark, rocky formation or small island in the water with a white bird perched on it. * **Hills/Landmass:** In the background, there are hills or mountains on the far shore. * **Clear Sky:** The sky is clear and bright blue, suggesting fair weather. It's a scenic photograph capturing the bridge and the coastal environment.<turn|> Prompting with multiple images¶ You can provide multiple images in a single prompt by including multiple image content in prompt template. from PIL import Image from IPython.display import display import requests from transformers import GenerationConfig config = GenerationConfig.from_pretrained(MODEL_ID) config.max_new_tokens = 512 gen_kwargs = dict(generation_config=config) img_urls = [ "https://gemma.ai/assets/capabilities/surprise.png", "https://gemma.ai/assets/capabilities/kitchen.jpg", ] for img in img_urls: display(Image.open(requests.get(img, stream=True).raw)) messages = [ { "role": "user", "content": [ {"type": "image", "url": img_urls[0]}, {"type": "image", "url": img_urls[1]}, {"type": "text", "text": "Caption these images."} ] } ] output = vqa_pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs) print(output[0]['generated_text']) Here are captions for the two images you provided: **Image 1: Black and White Cat** **Short & Sweet:** * Pure elegance. * Mischief in black and white. * Those emerald eyes. * A portrait of feline charm. **Descriptive & Engaging:** * The captivating gaze of a beautiful tuxedo cat. * Alert, curious, and utterly stunning. * When your cat has that perfectly intense expression. * Black, white, and mesmerizing green eyes. **Funny/Playful:** * Plotting world domination, one glance at a time. * Judging your life choices. * Warning: May cause extreme cuteness overload. **Hashtags:** `#BlackCat #TuxedoCat #CatLover #FelineFriends #GreenEyes #PetPortrait #CatsofInstagram #CuteCat` *** **Image 2: Kitchen Scene with Wooden Table** **Short & Sweet:** * Kitchen vibes. * Morning prep. * Rustic kitchen charm. * Baking dreams. **Descriptive & Engaging:** * A cozy, bright kitchen setup ready for culinary adventures. * Wooden countertops and colorful accents make for the perfect workspace. * Gathering ingredients for a delicious day. * The heart of a home kitchen. **Focusing on the Style:** * Whimsical watercolor kitchen scene. * Warm tones and rustic textures in this lovely illustration. **Hashtags:** `#KitchenDecor #WatercolorArt #RusticKitchen #Cooking #HomeDecor #KitchenInspo #Foodie #Illustration #CozyVibes`<turn|> OCR (Optical Character Recognition)¶ Models can recognize multilingual texts in the image. from PIL import Image from IPython.display import display import requests from transformers import GenerationConfig config = GenerationConfig.from_pretrained(MODEL_ID) config.max_new_tokens = 512 gen_kwargs = dict(generation_config=config) img_url = "https://gemma.ai/assets/capabilities/cat.png" input_image = Image.open(requests.get(img_url, stream=True).raw) display(input_image) messages = [ { "role": "user", "content": [ {"type": "image", "url": img_url}, {"type": "text", "text": "What does the sign say?"} ] } ] output = vqa_pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs) print(output[0]['generated_text']) The sign in the image says: **猫に注意** (Neko ni chūi) - which means **"Caution: Cat"** or **"Beware of cats"**. Below that, it says: **何かします** (Nanika shimasu) - which means **"I will do something"** or **"I will do something about it"**. In the context of the picture (showing a cat playfully jumping), the sign is likely humorous or a lighthearted warning.<turn|> Object Detection¶ Models are trained to detect objects in an image and get their bounding box coordinates. Bounding box coordinates are expressed as normalized values relative to a 1000x1000 grid. You need to descale these coordinates based on your original image size. import numpy as np from PIL import Image from IPython.display import display import requests import cv2 import re, json from transformers import GenerationConfig config = GenerationConfig.from_pretrained(MODEL_ID) config.max_new_tokens = 512 gen_kwargs = dict(generation_config=config) # Load Image img_url = "https://raw.githubusercontent.com/bebechien/gemma/refs/heads/main/PaliGemma_Demo.JPG" input_image = Image.open(requests.get(img_url, stream=True).raw) ############################### # some helper functions below # ############################### def draw_bounding_box(image, coordinates, label, label_colors, width, height): y1, x1, y2, x2 = [int(coord)/1000 for coord in coordinates] y1, x1, y2, x2 = map(round, (y1*height, x1*width, y2*height, x2*width)) text_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 3) text_width, text_height = text_size text_x = x1 + 2 text_y = y1 - 5 font_scale = 1 label_rect_width = text_width + 8 label_rect_height = int(text_height * font_scale) color = label_colors.get(label, None) if color is None: color = np.random.randint(0, 256, (3,)).tolist() label_colors[label] = color cv2.rectangle(image, (x1, y1 - label_rect_height), (x1 + label_rect_width, y1), color, -1) thickness = 2 cv2.putText(image, label, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), thickness, cv2.LINE_AA) cv2.rectangle(image, (x1, y1), (x2, y2), color, 2) return image def draw_results(text_content): match = re.search(r'```json\s+(.*?)\s+```', text_content, re.DOTALL) if match: json_string = match.group(1) # Parse the string into a Python list/object data_list = json.loads(json_string) labels = [] label_colors = {} output_image = input_image output_img = np.array(input_image) for item in data_list: width = input_image.size[0] height = input_image.size[1] # Draw bounding boxes on the frame. image = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR) output_img = draw_bounding_box(output_img, item["box_2d"], item["label"], label_colors, width, height) output_image = Image.fromarray(output_img) return output_image else: print("No JSON code block found.") messages = [ { "role": "user", "content": [ {"type": "image", "url": img_url}, {"type": "text", "text": "detect person and cat"} ] } ] output = vqa_pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs) print(output[0]['generated_text']) draw_results(output[0]['generated_text']) ```json [ {"box_2d": [243, 252, 956, 415], "label": "person"}, {"box_2d": [356, 606, 654, 802], "label": "cat"} ] ```<turn|> Variable Resolution (Token Budget)¶ All Gemma 4 models support variable resolution which means that images of different resolutions can be processed. Moreover, you can decide if you want to process a given image in a higher or lower resolution. If you are performing object detection, for instance, you might want to process the image in a higher resolution. Video understanding, for instance, can be done with a lower resolution for each frame to speed up inference. Essentially, it is a tradeoff between inference speed and accuracy of the image representations. This choice is controlled by the token budget, which represents the maximum number of visual tokens (also called visual token embeddings) that are generated for a given image. The user can decide between budget sizes of 70, 140, 280, 560, or 1120 tokens. Depending on the budget, the input is resized. If you have a higher budget (like 1120 tokens), then your image can maintain a higher resolution and as a result will have many more patches to process. If you have a lower budget (like 70 tokens), then your image needs to be downscaled and you will have fewer patches that need to be processed. With a higher budget (and therefore more tokens), you can capture much more information than with a lower budget. This budget determines how much the image is resized. Imagine you have a budget of 280 tokens, then the maximum number of patches will be 9 x 280 = 2,520. Why times 9? That's because in the next step, every 3x3 block of neighboring patches are merged into a single embedding