成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

如何使用Google Gemini模型完成計算機視覺任務? 原創

發布于 2025-5-26 08:31
瀏覽
0收藏

本文介紹如何使用Google Gemini模型完成計算機視覺任務的各個步驟,包括環境設置、圖像發送及模型輸出解釋等,還將探討數據注釋工具,以提供自定義訓練場景的上下文。

自從人工智能聊天機器人興起以來,Google Gemini脫穎而出,已經成為推動智能系統進化的主要參與者之一。除了強大的會話能力之外,Gemini還釋放了計算機視覺實際應用的潛力,讓它們能夠看到、解釋和描述周圍的世界。

本文將逐步講解如何利用Google Gemini完成計算機視覺任務,其中包括如何設置環境,發送帶有指令的圖像以及解釋模型的輸出以進行對象檢測、字幕生成和OCR,還將探討數據注釋工具(例如YOLO中使用的工具),為自定義訓練場景提供上下文。

Google Gemini簡介

Google Gemini是一系列用于處理多種數據類型(例如文本、圖像、音頻和代碼等)的人工智能模型,這意味著它可以處理涉及理解圖片和文字的任務。

Gemini 2.5 Pro的關鍵特性

?多模態輸入:在請求中接受文本和圖像的組合。

?推理:該模型可以分析輸入的信息,以執行識別物體或描述場景等任務。

?指令跟隨:響應指導其分析圖像的文本指令(提示)。

這些特性允許開發人員通過API將Google Gemini用于與視覺相關的任務,而無需為每個任務訓練單獨的模型。

數據注釋的作用:YOLO注釋器

盡管Gemini模型在計算機視覺任務中具備強大的零樣本或小樣本學習能力,但構建高度專業化的計算機視覺模型需要在針對特定問題量身定制的數據集上進行訓練。這就是數據注釋變得至關重要的地方,特別是對于像訓練自定義對象檢測器這樣的監督學習任務。

YOLO注釋器(通常指的是與YOLO格式兼容的工具,例如Labeling、CVAT或Roboflow)被設計用于創建標記數據集。

什么是數據注釋?

如何使用Google Gemini模型完成計算機視覺任務?-AI.x社區

圖像來源:??鏈接???

對于對象檢測,注釋涉及在圖像中每個感興趣的對象周圍繪制邊界框,并分配類標簽(例如“汽車”、“人”、“狗”)。這些注釋數據告訴模型在訓練期間要查找什么以及在哪里。

注釋工具的主要特性(例如YOLO注釋器)

  • 用戶界面:它們提供圖形界面,允許用戶加載圖像,繪制框(或多邊形,關鍵點等),并有效地分配標簽。
  • 格式兼容性:為YOLO模型設計的工具以YOLO訓練腳本期望的特定文本文件格式保存注釋(通常每個圖像一個.txt文件,包含類索引和規范化邊界框坐標)。
  • 效率特性:許多工具包括熱鍵、自動保存和模型輔助標記等特性,以加快通常耗時的注釋過程。批處理允許更有效地處理大型圖像集。
  • 集成:使用像YOLO這樣的標準格式確保注釋數據可以輕松地與流行的訓練框架(包括Ultralytics YOLO)一起使用。

雖然用于計算機視覺的Google Gemini可以在沒有事先注釋的情況下檢測對象,但如果需要一個模型來檢測具體的定制對象(例如獨特類型的工業設備、特定的產品缺陷等),可能需要收集圖像,并使用像YOLO注釋器這樣的工具對它們進行注釋,以訓練專用的YOLO模型。

代碼實現——Google Gemin用于計算機視覺

首先,需要安裝必要的軟件庫。

步驟1:安裝先決條件

(1)安裝庫

在終端運行以下命令:

!uv pip install -U -q google-genai ultralytics

該命令安裝google-genai庫,以便與Gemini API和ultralytics庫通信,后者包含處理圖像和在圖像上繪圖的有用功能。

(2)導入模塊

將這些行添加到Python Notebook中:

import json
import cv2
import ultralytics
from google import genai
from google.genai import types
from PIL import Image
from ultralytics.utils.downloads import safe_download
from ultralytics.utils.plotting import Annotator, colors
ultralytics.checks()

這段代碼導入了用于讀取圖像(cv2、PIL)、處理JSON數據(JSON)、與API交互(google.generativeai)和實用程序函數(ultralytics)等任務的庫。

(3)配置API密鑰

使用Google AI API密鑰初始化客戶端。

首先,需要安裝必要的軟件庫。

# Replace "your_api_key" with your actual key
# Use GenerativeModel for newer versions of the library
# Initialize the Gemini client with your API key
client = genai.Client(api_key=”your_api_key”)

這一步驟準備腳本以發送經過身份驗證的請求。

步驟2:與Gemini互動

創建一個向模型發送請求的函數。這個函數接受一個圖像和一個文本提示,并返回模型的文本輸出。

def inference(image, prompt, temp=0.5):
 """
 Performs inference using Google Gemini 2.5 Pro Experimental model.
 Args:
 image (str or genai.types.Blob): The image input, either as a base64-encoded string or Blob object.
 prompt (str): A text prompt to guide the model's response.
 temp (float, optional): Sampling temperature for response randomness. Default is 0.5.
 Returns:
 str: The text response generated by the Gemini model based on the prompt and image.
 """
 response = client.models.generate_content(
 model="gemini-2.5-pro-exp-03-25",
 cnotallow=[prompt, image], # Provide both the text prompt and image as input
 cnotallow=types.GenerateContentConfig(
 temperature=temp, # Controls creativity vs. determinism in output
 ),
 )
 return response.text # Return the generated textual response

解釋

(1)該函數將圖像和文本指令(提示)發送到model_client中指定的Gemini模型。

(2)溫度設置(溫度)影響輸出的隨機性;值越低,結果越可預測。

步驟3:準備圖像數據

在將圖像發送到模型之前,需要正確加載圖像。如果需要,該函數可以下載圖像,讀取圖像,轉換顏色格式,并返回PIL image對象及其尺寸。

def read_image(filename):
 image_name = safe_download(filename)
 # Read image with opencv
 image = cv2.cvtColor(cv2.imread(f"/content/{image_name}"), cv2.COLOR_BGR2RGB)
 # Extract width and height
 h, w = image.shape[:2]
 # # Read the image using OpenCV and convert it into the PIL format
 return Image.fromarray(image), w, h

解釋

(1)該函數使用OpenCV (cv2)讀取圖像文件。

(2)它將圖像顏色順序轉換為RGB,這是標準的。

(3)它返回圖像作為一個PIL對象,適合于推理函數,以及它的寬度和高度。

步驟4:結果格式化

def clean_results(results):
 """Clean the results for visualization."""
 return results.strip().removeprefix("```json").removesuffix("```").strip()

該函數將結果格式化為JSON格式。

任務1:對象檢測

Gemini可以在圖像中找到對象,并根據文本指示報告其位置(邊界框)。

# Define the text prompt
prompt = """
Detect the 2d bounding boxes of objects in image.
"""
# Fixed, plotting function depends on this.
output_prompt = "Return just box_2d and labels, no additional text."
image, w, h = read_image("https://media-cldnry.s-nbcnews.com/image/upload/t_fit-1000w,f_auto,q_auto:best/newscms/2019_02/2706861/190107-messy-desk-stock-cs-910a.jpg") # Read img, extract width, height
results = inference(image, prompt + output_prompt) # Perform inference
cln_results = json.loads(clean_results(results)) # Clean results, list convert
annotator = Annotator(image) # initialize Ultralytics annotator
for idx, item in enumerate(cln_results):
 # By default, gemini model return output with y coordinates first.
 # Scale normalized box coordinates (0–1000) to image dimensions
 y1, x1, y2, x2 = item["box_2d"] # bbox post processing,
 y1 = y1 / 1000 * h
 x1 = x1 / 1000 * w
 y2 = y2 / 1000 * h
 x2 = x2 / 1000 * w
 if x1 > x2:
 x1, x2 = x2, x1 # Swap x-coordinates if needed
 if y1 > y2:
 y1, y2 = y2, y1 # Swap y-coordinates if needed
 annotator.box_label([x1, y1, x2, y2], label=item["label"], color=colors(idx, True))
Image.fromarray(annotator.result()) # display the output

輸出

如何使用Google Gemini模型完成計算機視覺任務?-AI.x社區

圖像來源:??鏈接???

解釋

(1)提示告訴模型要查找什么以及如何格式化輸出(JSON)。

(2)它使用圖像寬度(w)和高度(h)將歸一化的邊界框框坐標(0-1000)轉換為像素坐標。

(3)注釋器工具在圖像的副本上繪制框和標簽。

任務2:測試推理能力

使用Gemini模型,可以使用理解上下文并提供更精確結果的高級推理來處理復雜任務。

# Define the text prompt
prompt = """
Detect the 2d bounding box around:
highlight the area of morning light +
PC on table
potted plant
coffee cup on table
"""
# Fixed, plotting function depends on this.
output_prompt = "Return just box_2d and labels, no additional text."
image, w, h = read_image("https://thumbs.dreamstime.com/b/modern-office-workspace-laptop-coffee-cup-cityscape-sunrise-sleek-desk-featuring-stationery-organized-neatly-city-345762953.jpg") # Read image and extract width, height
results = inference(image, prompt + output_prompt)
# Clean the results and load results in list format
cln_results = json.loads(clean_results(results))
annotator = Annotator(image) # initialize Ultralytics annotator
for idx, item in enumerate(cln_results):
 # By default, gemini model return output with y coordinates first.
 # Scale normalized box coordinates (0–1000) to image dimensions
 y1, x1, y2, x2 = item["box_2d"] # bbox post processing,
 y1 = y1 / 1000 * h
 x1 = x1 / 1000 * w
 y2 = y2 / 1000 * h
 x2 = x2 / 1000 * w
 if x1 > x2:
 x1, x2 = x2, x1 # Swap x-coordinates if needed
 if y1 > y2:
 y1, y2 = y2, y1 # Swap y-coordinates if needed
 annotator.box_label([x1, y1, x2, y2], label=item["label"], color=colors(idx, True))
Image.fromarray(annotator.result()) # display the output

輸出

如何使用Google Gemini模型完成計算機視覺任務?-AI.x社區

圖像來源:??鏈接???

解釋

(1)該代碼塊包含一個復雜的提示,用于測試模型的推理能力。

(2)它使用圖像寬度(w)和高度(h)將歸一化邊界框框坐標(0-1000)轉換為像素坐標。

(3)注釋器工具在圖像的副本上繪制框和標簽。

任務3:圖像字幕

Gemini可以為圖片創建文字描述。

# Define the text prompt
prompt = """
What's inside the image, generate a detailed captioning in the form of short
story, Make 4-5 lines and start each sentence on a new line.
"""
image, _, _ = read_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg") # Read image and extract width, height
plt.imshow(image)
plt.axis('off') # Hide axes
plt.show()
print(inference(image, prompt)) # Display the results

輸出

如何使用Google Gemini模型完成計算機視覺任務?-AI.x社區

圖像來源:??鏈接???

解釋

(1)這個提示要求模型以特定風格生成描述(如敘事風格,限制為4行,并且每行獨立成段)。

(2)所提供的圖像顯示在輸出中。

(3)函數返回生成的文本。這對于創建所有文本或摘要非常有用。

任務4:光學字符識別(OCR)

Gemini可以讀取圖像中的文本,并告訴它在哪里找到了文本。

# Define the text prompt
prompt = """
Extract the text from the image
"""
# Fixed, plotting function depends on this.
output_prompt = """
Return just box_2d which will be location of detected text areas + label"""
image, w, h = read_image("https://cdn.mos.cms.futurecdn.net/4sUeciYBZHaLoMa5KiYw7h-1200-80.jpg") # Read image and extract width, height
results = inference(image, prompt + output_prompt)
# Clean the results and load results in list format
cln_results = json.loads(clean_results(results))
print()
annotator = Annotator(image) # initialize Ultralytics annotator
for idx, item in enumerate(cln_results):
 # By default, gemini model return output with y coordinates first.
 # Scale normalized box coordinates (0–1000) to image dimensions
 y1, x1, y2, x2 = item["box_2d"] # bbox post processing,
 y1 = y1 / 1000 * h
 x1 = x1 / 1000 * w
 y2 = y2 / 1000 * h
 x2 = x2 / 1000 * w
 if x1 > x2:
 x1, x2 = x2, x1 # Swap x-coordinates if needed
 if y1 > y2:
 y1, y2 = y2, y1 # Swap y-coordinates if needed
 annotator.box_label([x1, y1, x2, y2], label=item["label"], color=colors(idx, True))
Image.fromarray(annotator.result()) # display the output

輸出

如何使用Google Gemini模型完成計算機視覺任務?-AI.x社區

圖像來源:??鏈接???

解釋

(1)它使用一個類似于對象檢測的提示符,但要求輸入文本(標簽)而不是對象名稱。

(2)代碼提取文本及其位置,打印文本內容,并在圖像上繪制對應的邊界框。

(3)這對于數字化文檔或從照片中的標志或標簽中讀取文本非常有用。

結論

通過簡單的API調用,用于計算機視覺的代碼段可以輕松處理對象檢測、圖像字幕和OCR等任務。通過發送圖像以及清晰的文本說明,可以指導模型的理解,并獲得可用的實時結果。

也就是說,雖然Gemini非常適合通用任務或快速實驗,但它并不總是最適合高度專業化的用例。例如,當需要識別小眾對象或對準確性有更高要求時,傳統方法依然具有優勢:收集數據集,使用YOLO標簽器等工具對其進行注釋,并根據需求訓練定制模型。
原文標題:??How to Use Google Gemini Models for Computer Vision Tasks???,作者:Harsh Mishra

?著作權歸作者所有,如需轉載,請注明出處,否則將追究法律責任
已于2025-5-26 10:16:00修改
收藏
回復
舉報
回復
相關推薦
主站蜘蛛池模板: 91免费看片| 日韩欧美亚洲 | www.久| 免费国产成人av | 国产美女黄色片 | a级片在线观看 | 色视频成人在线观看免 | 久久狠狠 | 日韩三级在线观看 | 亚洲最大福利网 | 国产乱码精品一区二三赶尸艳谈 | 久久久久久久一区 | 精品无码三级在线观看视频 | 草久在线视频 | 人人九九 | 欧美一级二级三级视频 | 日韩黄 | 99久久久无码国产精品 | 欧美精品一区二区三区蜜桃视频 | 99re6在线视频精品免费 | 日本在线观看视频 | 伊人伊人网 | 日韩a视频 | 久久久久久久电影 | 欧美亚洲一区二区三区 | 国产精品视频一二三区 | 日韩三级一区 | 国产精品永久久久久久久www | 在线观看国产 | 日韩中文字幕免费在线观看 | 成人av在线大片 | 一区二区三区日 | 日本网站免费在线观看 | 成人欧美一区二区三区在线观看 | 熟女毛片 | 久久一区视频 | 精品久久久久一区二区国产 | 国产精品视频专区 | 欧美久久久久久久 | 中文字幕一区二区三区乱码图片 | 大象视频一区二区 |