Spaces:
Runtime error
Runtime error
Zero-shot object detection on videos using PaliGemma.
Browse files
app.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image, ImageDraw, ImageFont
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
from transformers import AutoTokenizer, PaliGemmaForConditionalGeneration, PaliGemmaProcessor
|
5 |
+
import torch
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
# Load PaliGemma
|
9 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
10 |
+
model_id = "google/paligemma-3b-mix-224"
|
11 |
+
model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(device)
|
12 |
+
processor = PaliGemmaProcessor.from_pretrained(model_id)
|
13 |
+
|
14 |
+
# Function to draw bounding boxes (your original code)
|
15 |
+
def draw_bounding_box(draw, coordinates, label, width, height):
|
16 |
+
y1, x1, y2, x2 = coordinates
|
17 |
+
y1, x1, y2, x2 = map(round, (y1*height, x1*width, y2*height, x2*width))
|
18 |
+
|
19 |
+
text_width, text_height = draw.textsize(label)
|
20 |
+
draw.rectangle([(x1, y1 - text_height - 2), (x1 + text_width + 4, y1)], fill="red")
|
21 |
+
|
22 |
+
# Draw label text
|
23 |
+
draw.text((x1 + 2, y1 - text_height - 2), label, fill="white")
|
24 |
+
|
25 |
+
# Draw bounding box
|
26 |
+
draw.rectangle([(x1, y1), (x2, y2)], outline="red", width=2)
|
27 |
+
|
28 |
+
def process_video(video_path, input_text):
|
29 |
+
cap = cv2.VideoCapture(video_path)
|
30 |
+
fourcc = cv2.VideoWriter_fourcc(*'XVID')
|
31 |
+
out = cv2.VideoWriter('output_paligemma_keras.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))
|
32 |
+
|
33 |
+
while(True):
|
34 |
+
ret, frame = cap.read()
|
35 |
+
if not ret:
|
36 |
+
break
|
37 |
+
|
38 |
+
# Convert the frame to a PIL Image
|
39 |
+
img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
40 |
+
|
41 |
+
# Send text prompt and image as input.
|
42 |
+
inputs = processor(text=input_text, images=img,
|
43 |
+
padding="longest", do_convert_rgb=True, return_tensors="pt").to("cuda")
|
44 |
+
inputs = inputs.to(dtype=model.dtype)
|
45 |
+
|
46 |
+
# Get output.
|
47 |
+
with torch.no_grad():
|
48 |
+
output = model.generate(**inputs, max_length=496)
|
49 |
+
|
50 |
+
paligemma_response = processor.decode(output[0], skip_special_tokens=True)[len(input_text):].lstrip("\n")
|
51 |
+
# print(paligemma_response) # For debugging
|
52 |
+
|
53 |
+
detections = paligemma_response.split(" ; ")
|
54 |
+
|
55 |
+
# Parse the output bounding box coordinates
|
56 |
+
parsed_coordinates = []
|
57 |
+
labels = []
|
58 |
+
|
59 |
+
for item in detections:
|
60 |
+
# Remove '<loc>' tags and split the string
|
61 |
+
# print(item)
|
62 |
+
detection = item.replace("<loc", "").split()
|
63 |
+
|
64 |
+
if len(detection) >= 2:
|
65 |
+
coordinates_str = detection[0]
|
66 |
+
label = detection[1]
|
67 |
+
labels.append(label)
|
68 |
+
else:
|
69 |
+
# No label detected, skip the iteration.
|
70 |
+
continue
|
71 |
+
|
72 |
+
# Split the coordinates string by '>' to get individual coordinates
|
73 |
+
coordinates = coordinates_str.split(">")
|
74 |
+
coordinates = coordinates[:4] # Slicing to ensure only 4 values
|
75 |
+
|
76 |
+
if coordinates[-1] == '':
|
77 |
+
coordinates = coordinates[:-1]
|
78 |
+
# print(coordinates)
|
79 |
+
|
80 |
+
coordinates = [int(coord)/1024 for coord in coordinates]
|
81 |
+
# location_values = [int(loc) for loc in re.findall(r'\d{4}', coordinates)]
|
82 |
+
# y1, x1, y2, x2 = [value / 1024 for value in location_values]
|
83 |
+
parsed_coordinates.append(coordinates)
|
84 |
+
|
85 |
+
width = img.size[0]
|
86 |
+
height = img.size[1]
|
87 |
+
|
88 |
+
# Draw bounding boxes on the frame using PIL
|
89 |
+
draw = ImageDraw.Draw(img)
|
90 |
+
for coordinates, label in zip(parsed_coordinates, labels):
|
91 |
+
draw_bounding_box(draw, coordinates, label, width=width, height=height)
|
92 |
+
|
93 |
+
# Convert the PIL Image back to OpenCV format
|
94 |
+
frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
95 |
+
|
96 |
+
# Write the frame to the output video
|
97 |
+
out.write(frame)
|
98 |
+
|
99 |
+
cap.release()
|
100 |
+
out.release()
|
101 |
+
|
102 |
+
return "output_paligemma_keras.avi"
|
103 |
+
|
104 |
+
demo = gr.Interface(
|
105 |
+
fn=process_video,
|
106 |
+
inputs=[gr.Video(label="Input Video"), gr.Textbox(label="detect <class-name>")],
|
107 |
+
outputs=[gr.Video(label="Output Video")],
|
108 |
+
title="PaliGemma Object Detection",
|
109 |
+
description="Upload a video and specify the object you want to detect."
|
110 |
+
)
|
111 |
+
|
112 |
+
demo.launch(share=True)
|