点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达
# Install Generative AI SDK.
!pip install -q -U google-generativeai
# Import libraries
from google.colab import userdata
import google.generativeai as genai
import re
from PIL import Image
import cv2
import numpy as np
API_KEY = userdata.get('gemini')
genai.configure(api_key=API_KEY)
model = genai.GenerativeModel(model_name='gemini-1.5-pro')
input_image = "image.jpg" # @param {type : 'string'}
img = Image.open(input_image)
response = model.generate_content([
img,
(
"Return bounding boxes for all objects in the image in the following format as"
" a list. \n [ymin, xmin, ymax, xmax, object_name]. If there are more than one object, return separate lists for each object"
),
])
result = response.text
def parse_bounding_box(response):
bounding_boxes = re.findall(r'\[(\d+,\s*\d+,\s*\d+,\s*\d+,\s*[\w\s]+)\]', response)
# Convert each group into a list of integers and labels.
parsed_boxes = []
for box in bounding_boxes:
parts = box.split(',')
numbers = list(map(int, parts[:-1]))
label = parts[-1].strip()
parsed_boxes.append((numbers, label))
# Return the list of bounding boxes with their labels.
return parsed_boxes
bounding_box = parse_bounding_box(result)
label_colors = {}
def draw_bounding_boxes(image, bounding_boxes_with_labels):
if image.mode != 'RGB':
image = image.convert('RGB')
image = np.array(image)
for bounding_box, label in bounding_boxes_with_labels:
# Normalize the bounding box coordinates.
height = image.shape[1], image.shape[0]
xmin, ymax, xmax = bounding_box
x1 = int(xmin / 1000 * width)
y1 = int(ymin / 1000 * height)
x2 = int(xmax / 1000 * width)
y2 = int(ymax / 1000 * height)
if label not in label_colors:
color = np.random.randint(0, 256, (3,)).tolist()
color =
else:
color = label_colors[label]
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
font_thickness = 1
box_thickness = 2
text_size = cv2.getTextSize(label, font, font_scale, font_thickness)[0]
text_bg_x1 = x1
text_bg_y1 = y1 - text_size[1] - 5
text_bg_x2 = x1 + text_size[0] + 8
text_bg_y2 = y1
(text_bg_x1, text_bg_y1), (text_bg_x2, text_bg_y2), color, -1)
label, (x1 + 2, y1 - 5), font, font_scale, (255, 255, 255), font_thickness)
(x1, y1), (x2, y2), color, box_thickness)
image = Image.fromarray(image)
return image
output = draw_bounding_boxes(img, bounding_box)
下载1:OpenCV-Contrib扩展模块中文版教程 在「小白学视觉」公众号后台回复:扩展模块中文教程,即可下载全网第一份OpenCV扩展模块教程中文版,涵盖扩展模块安装、SFM算法、立体视觉、目标跟踪、生物视觉、超分辨率处理等二十多章内容。 下载2:Python视觉实战项目52讲 在「小白学视觉」公众号后台回复:Python视觉实战项目,即可下载包括图像分割、口罩检测、车道线检测、车辆计数、添加眼线、车牌识别、字符识别、情绪检测、文本内容提取、面部识别等31个视觉实战项目,助力快速学校计算机视觉。 下载3:OpenCV实战项目20讲 在「小白学视觉」公众号后台回复:OpenCV实战项目20讲,即可下载含有20个基于OpenCV实现20个实战项目,实现OpenCV学习进阶。 交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~