696 lines
17 KiB
Python
696 lines
17 KiB
Python
|
|
import os
|
|
import time
|
|
import tempfile
|
|
from io import BytesIO
|
|
|
|
import cv2
|
|
import numpy as np
|
|
import pandas as pd
|
|
import streamlit as st
|
|
import torch
|
|
|
|
from PIL import Image
|
|
from transformers import (
|
|
AutoProcessor,
|
|
AutoModelForZeroShotObjectDetection
|
|
)
|
|
from ultralytics import YOLOWorld
|
|
|
|
|
|
# --------------------------------------------------
|
|
# APPLICATION CONFIGURATION
|
|
# --------------------------------------------------
|
|
|
|
st.set_page_config(
|
|
page_title="Open-Vocabulary Object Detection",
|
|
page_icon="🎯",
|
|
layout="wide"
|
|
)
|
|
|
|
st.title("Open-Vocabulary Object Detection")
|
|
st.caption("Grounding DINO vs YOLO-World | Zero-shot object detection")
|
|
|
|
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
if DEVICE == "cuda":
|
|
GPU_NAME = torch.cuda.get_device_name(0)
|
|
else:
|
|
GPU_NAME = "CPU"
|
|
|
|
st.sidebar.header("System Information")
|
|
st.sidebar.success(f"Processing device: {DEVICE}")
|
|
st.sidebar.write(f"Hardware: {GPU_NAME}")
|
|
|
|
if DEVICE == "cuda":
|
|
props = torch.cuda.get_device_properties(0)
|
|
st.sidebar.write(
|
|
f"GPU memory: {props.total_memory / 1024**3:.2f} GB"
|
|
)
|
|
|
|
|
|
# --------------------------------------------------
|
|
# IMAGE CONVERSION
|
|
# --------------------------------------------------
|
|
|
|
def pil_to_bytes(image):
|
|
buffer = BytesIO()
|
|
image.save(buffer, format="PNG")
|
|
return buffer.getvalue()
|
|
|
|
|
|
# --------------------------------------------------
|
|
# MODEL LOADING
|
|
# Only the selected model is loaded.
|
|
# --------------------------------------------------
|
|
|
|
@st.cache_resource
|
|
def load_grounding_dino():
|
|
|
|
model_id = "IDEA-Research/grounding-dino-tiny"
|
|
|
|
processor = AutoProcessor.from_pretrained(model_id)
|
|
|
|
model = AutoModelForZeroShotObjectDetection.from_pretrained(
|
|
model_id
|
|
).to(DEVICE)
|
|
|
|
model.eval()
|
|
|
|
return processor, model
|
|
|
|
|
|
@st.cache_resource
|
|
def load_yolo_world():
|
|
|
|
model = YOLOWorld("yolov8s-world.pt")
|
|
|
|
return model
|
|
|
|
|
|
# --------------------------------------------------
|
|
# GPU SYNCHRONIZATION
|
|
# --------------------------------------------------
|
|
|
|
def synchronize_gpu():
|
|
|
|
if DEVICE == "cuda":
|
|
torch.cuda.synchronize()
|
|
|
|
|
|
# --------------------------------------------------
|
|
# GROUNDING DINO DETECTION
|
|
# --------------------------------------------------
|
|
|
|
def detect_dino(image, labels, threshold):
|
|
|
|
processor, model = load_grounding_dino()
|
|
|
|
text_prompt = ". ".join(labels) + "."
|
|
|
|
inputs = processor(
|
|
images=image,
|
|
text=text_prompt,
|
|
return_tensors="pt"
|
|
).to(DEVICE)
|
|
|
|
synchronize_gpu()
|
|
|
|
start_time = time.perf_counter()
|
|
|
|
with torch.inference_mode():
|
|
outputs = model(**inputs)
|
|
|
|
synchronize_gpu()
|
|
|
|
inference_time = (
|
|
time.perf_counter() - start_time
|
|
) * 1000
|
|
|
|
results = processor.post_process_grounded_object_detection(
|
|
outputs,
|
|
inputs.input_ids,
|
|
threshold=threshold,
|
|
text_threshold=0.25,
|
|
target_sizes=[(image.height, image.width)]
|
|
)[0]
|
|
|
|
annotated = np.array(image).copy()
|
|
|
|
detections = []
|
|
|
|
returned_labels = results.get(
|
|
"text_labels",
|
|
results.get("labels", [])
|
|
)
|
|
|
|
for box, score, label in zip(
|
|
results["boxes"],
|
|
results["scores"],
|
|
returned_labels
|
|
):
|
|
|
|
x1, y1, x2, y2 = map(int, box.tolist())
|
|
|
|
confidence = float(score)
|
|
|
|
label = str(label)
|
|
|
|
cv2.rectangle(
|
|
annotated,
|
|
(x1, y1),
|
|
(x2, y2),
|
|
(0, 255, 0),
|
|
2
|
|
)
|
|
|
|
cv2.putText(
|
|
annotated,
|
|
f"{label} {confidence:.2f}",
|
|
(x1, max(20, y1 - 8)),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.6,
|
|
(0, 255, 0),
|
|
2
|
|
)
|
|
|
|
detections.append({
|
|
"Object": label,
|
|
"Confidence": round(confidence, 3)
|
|
})
|
|
|
|
return Image.fromarray(annotated), detections, inference_time
|
|
|
|
|
|
# --------------------------------------------------
|
|
# YOLO-WORLD DETECTION
|
|
# --------------------------------------------------
|
|
|
|
def detect_yolo(image, labels, threshold):
|
|
|
|
model = load_yolo_world()
|
|
|
|
model.set_classes(labels)
|
|
|
|
synchronize_gpu()
|
|
|
|
start_time = time.perf_counter()
|
|
|
|
results = model.predict(
|
|
source=image,
|
|
device=0 if DEVICE == "cuda" else "cpu",
|
|
conf=threshold,
|
|
imgsz=640,
|
|
verbose=False
|
|
)
|
|
|
|
synchronize_gpu()
|
|
|
|
inference_time = (
|
|
time.perf_counter() - start_time
|
|
) * 1000
|
|
|
|
result = results[0]
|
|
|
|
annotated = result.plot()
|
|
|
|
detections = []
|
|
|
|
if result.boxes is not None:
|
|
|
|
for box in result.boxes:
|
|
|
|
class_id = int(box.cls[0])
|
|
confidence = float(box.conf[0])
|
|
|
|
detections.append({
|
|
"Object": result.names[class_id],
|
|
"Confidence": round(confidence, 3)
|
|
})
|
|
|
|
annotated = cv2.cvtColor(
|
|
annotated,
|
|
cv2.COLOR_BGR2RGB
|
|
)
|
|
|
|
return Image.fromarray(annotated), detections, inference_time
|
|
|
|
|
|
# --------------------------------------------------
|
|
# COMMON DETECTION FUNCTION
|
|
# --------------------------------------------------
|
|
|
|
def run_detection(image, model_choice, labels, threshold):
|
|
|
|
if model_choice == "Grounding DINO":
|
|
|
|
return detect_dino(
|
|
image,
|
|
labels,
|
|
threshold
|
|
)
|
|
|
|
return detect_yolo(
|
|
image,
|
|
labels,
|
|
threshold
|
|
)
|
|
|
|
|
|
# --------------------------------------------------
|
|
# USER INTERFACE
|
|
# --------------------------------------------------
|
|
|
|
st.divider()
|
|
|
|
model_choice = st.selectbox(
|
|
"Select detection model",
|
|
["Grounding DINO", "YOLO-World"]
|
|
)
|
|
|
|
input_type = st.radio(
|
|
"Select input type",
|
|
["Image", "Video"],
|
|
horizontal=True
|
|
)
|
|
|
|
prompt = st.text_input(
|
|
"Enter object categories (comma separated)",
|
|
"person, car, motorcycle, bus, truck, bicycle"
|
|
)
|
|
|
|
threshold = st.slider(
|
|
"Confidence threshold",
|
|
min_value=0.10,
|
|
max_value=0.80,
|
|
value=0.25,
|
|
step=0.05
|
|
)
|
|
|
|
uploaded = st.file_uploader(
|
|
"Upload an image or video",
|
|
type=["jpg", "jpeg", "png", "mp4", "avi", "mov"]
|
|
)
|
|
|
|
if input_type == "Video":
|
|
|
|
max_frames = st.slider(
|
|
"Maximum video frames to process",
|
|
min_value=30,
|
|
max_value=300,
|
|
value=120,
|
|
step=30
|
|
)
|
|
|
|
else:
|
|
|
|
max_frames = 0
|
|
|
|
|
|
# --------------------------------------------------
|
|
# EXECUTE DETECTION
|
|
# --------------------------------------------------
|
|
|
|
if uploaded is not None and prompt.strip():
|
|
|
|
labels = [
|
|
item.strip()
|
|
for item in prompt.split(",")
|
|
if item.strip()
|
|
]
|
|
|
|
if st.button("Run Detection", type="primary"):
|
|
|
|
suffix = os.path.splitext(uploaded.name)[1]
|
|
|
|
input_path = None
|
|
output_path = None
|
|
|
|
try:
|
|
|
|
with tempfile.NamedTemporaryFile(
|
|
delete=False,
|
|
suffix=suffix
|
|
) as temp:
|
|
|
|
temp.write(uploaded.getvalue())
|
|
input_path = temp.name
|
|
|
|
# --------------------------------------
|
|
# IMAGE PROCESSING
|
|
# --------------------------------------
|
|
|
|
if input_type == "Image":
|
|
|
|
image = Image.open(input_path).convert("RGB")
|
|
|
|
with st.spinner(
|
|
f"Loading {model_choice} and detecting objects..."
|
|
):
|
|
|
|
output, detections, elapsed = run_detection(
|
|
image,
|
|
model_choice,
|
|
labels,
|
|
threshold
|
|
)
|
|
|
|
col1, col2 = st.columns(2)
|
|
|
|
with col1:
|
|
|
|
st.subheader("Original Image")
|
|
st.image(
|
|
image,
|
|
use_container_width=True
|
|
)
|
|
|
|
with col2:
|
|
|
|
st.subheader("Detection Result")
|
|
st.image(
|
|
output,
|
|
use_container_width=True
|
|
)
|
|
|
|
st.divider()
|
|
|
|
metric1, metric2, metric3 = st.columns(3)
|
|
|
|
metric1.metric(
|
|
"Inference Time",
|
|
f"{elapsed:.2f} ms"
|
|
)
|
|
|
|
metric2.metric(
|
|
"Detected Objects",
|
|
len(detections)
|
|
)
|
|
|
|
metric3.metric(
|
|
"Inference FPS",
|
|
f"{1000 / elapsed:.2f}" if elapsed > 0 else "N/A"
|
|
)
|
|
|
|
if detections:
|
|
|
|
st.subheader("Detection Details")
|
|
|
|
df = pd.DataFrame(detections)
|
|
|
|
st.dataframe(
|
|
df,
|
|
use_container_width=True
|
|
)
|
|
|
|
st.subheader("Object Counts")
|
|
|
|
counts = (
|
|
df["Object"]
|
|
.value_counts()
|
|
.rename_axis("Object")
|
|
.reset_index(name="Count")
|
|
)
|
|
|
|
st.dataframe(
|
|
counts,
|
|
use_container_width=True
|
|
)
|
|
|
|
else:
|
|
|
|
st.warning("No objects detected.")
|
|
|
|
st.download_button(
|
|
"Download Annotated Image",
|
|
data=pil_to_bytes(output),
|
|
file_name="detection_result.png",
|
|
mime="image/png"
|
|
)
|
|
|
|
# --------------------------------------
|
|
# VIDEO PROCESSING
|
|
# --------------------------------------
|
|
|
|
else:
|
|
|
|
cap = cv2.VideoCapture(input_path)
|
|
|
|
if not cap.isOpened():
|
|
|
|
st.error("Unable to open the uploaded video.")
|
|
|
|
else:
|
|
|
|
original_fps = cap.get(
|
|
cv2.CAP_PROP_FPS
|
|
)
|
|
|
|
if not original_fps or original_fps <= 0:
|
|
original_fps = 25
|
|
|
|
total_frames = int(
|
|
cap.get(cv2.CAP_PROP_FRAME_COUNT)
|
|
)
|
|
|
|
if total_frames <= 0:
|
|
total_frames = max_frames
|
|
|
|
frames_to_process = min(
|
|
total_frames,
|
|
max_frames
|
|
)
|
|
|
|
width = int(
|
|
cap.get(cv2.CAP_PROP_FRAME_WIDTH)
|
|
)
|
|
|
|
height = int(
|
|
cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
|
|
)
|
|
|
|
with tempfile.NamedTemporaryFile(
|
|
delete=False,
|
|
suffix=".mp4"
|
|
) as out_file:
|
|
|
|
output_path = out_file.name
|
|
|
|
writer = cv2.VideoWriter(
|
|
output_path,
|
|
cv2.VideoWriter_fourcc(*"mp4v"),
|
|
original_fps,
|
|
(width, height)
|
|
)
|
|
|
|
progress = st.progress(0)
|
|
status = st.empty()
|
|
|
|
frame_count = 0
|
|
inference_total = 0.0
|
|
object_totals = {}
|
|
|
|
with st.spinner("Processing video..."):
|
|
|
|
while frame_count < frames_to_process:
|
|
|
|
ret, frame = cap.read()
|
|
|
|
if not ret:
|
|
break
|
|
|
|
# Resize large frames while preserving
|
|
# their aspect ratio.
|
|
|
|
max_dimension = 960
|
|
|
|
h, w = frame.shape[:2]
|
|
|
|
scale = min(
|
|
1.0,
|
|
max_dimension / max(h, w)
|
|
)
|
|
|
|
if scale < 1.0:
|
|
|
|
frame = cv2.resize(
|
|
frame,
|
|
(
|
|
int(w * scale),
|
|
int(h * scale)
|
|
)
|
|
)
|
|
|
|
rgb = cv2.cvtColor(
|
|
frame,
|
|
cv2.COLOR_BGR2RGB
|
|
)
|
|
|
|
image = Image.fromarray(rgb)
|
|
|
|
result, detections, elapsed = run_detection(
|
|
image,
|
|
model_choice,
|
|
labels,
|
|
threshold
|
|
)
|
|
|
|
annotated = cv2.cvtColor(
|
|
np.array(result),
|
|
cv2.COLOR_RGB2BGR
|
|
)
|
|
|
|
# Restore original video dimensions.
|
|
if annotated.shape[1] != width or annotated.shape[0] != height:
|
|
|
|
annotated = cv2.resize(
|
|
annotated,
|
|
(width, height)
|
|
)
|
|
|
|
writer.write(annotated)
|
|
|
|
inference_total += elapsed
|
|
|
|
for detection in detections:
|
|
|
|
name = detection["Object"]
|
|
|
|
object_totals[name] = (
|
|
object_totals.get(name, 0) + 1
|
|
)
|
|
|
|
frame_count += 1
|
|
|
|
progress.progress(
|
|
min(
|
|
frame_count / frames_to_process,
|
|
1.0
|
|
)
|
|
)
|
|
|
|
status.write(
|
|
f"Processed {frame_count} / "
|
|
f"{frames_to_process} frames"
|
|
)
|
|
|
|
cap.release()
|
|
writer.release()
|
|
|
|
st.success("Video processing completed!")
|
|
|
|
avg_inference = (
|
|
inference_total / frame_count
|
|
if frame_count > 0 else 0
|
|
)
|
|
|
|
inference_fps = (
|
|
1000 / avg_inference
|
|
if avg_inference > 0 else 0
|
|
)
|
|
|
|
metric1, metric2, metric3 = st.columns(3)
|
|
|
|
metric1.metric(
|
|
"Processed Frames",
|
|
frame_count
|
|
)
|
|
|
|
metric2.metric(
|
|
"Average Inference Time",
|
|
f"{avg_inference:.2f} ms"
|
|
)
|
|
|
|
metric3.metric(
|
|
"Inference FPS",
|
|
f"{inference_fps:.2f}"
|
|
)
|
|
|
|
st.caption(
|
|
"Inference FPS measures model inference time, "
|
|
"not total video-processing speed."
|
|
)
|
|
|
|
if object_totals:
|
|
|
|
st.subheader("Object Detection Counts")
|
|
|
|
counts = pd.DataFrame(
|
|
[
|
|
{
|
|
"Object": name,
|
|
"Total detections across frames": count
|
|
}
|
|
for name, count in object_totals.items()
|
|
]
|
|
)
|
|
|
|
st.dataframe(
|
|
counts,
|
|
use_container_width=True
|
|
)
|
|
|
|
with open(output_path, "rb") as f:
|
|
|
|
video_data = f.read()
|
|
|
|
st.subheader("Processed Video")
|
|
|
|
st.video(video_data)
|
|
|
|
st.download_button(
|
|
"Download Processed Video",
|
|
data=video_data,
|
|
file_name="detected_video.mp4",
|
|
mime="video/mp4"
|
|
)
|
|
|
|
except Exception as e:
|
|
|
|
st.error("An error occurred during detection.")
|
|
st.exception(e)
|
|
|
|
finally:
|
|
|
|
if input_path and os.path.exists(input_path):
|
|
os.unlink(input_path)
|
|
|
|
if output_path and os.path.exists(output_path):
|
|
os.unlink(output_path)
|
|
|
|
|
|
# --------------------------------------------------
|
|
# GPU MONITORING
|
|
# --------------------------------------------------
|
|
|
|
st.divider()
|
|
|
|
st.subheader("System Performance")
|
|
|
|
st.write(f"**Processing Device:** {DEVICE}")
|
|
st.write(f"**GPU / CPU:** {GPU_NAME}")
|
|
|
|
if DEVICE == "cuda":
|
|
|
|
allocated = (
|
|
torch.cuda.memory_allocated() / 1024**2
|
|
)
|
|
|
|
reserved = (
|
|
torch.cuda.memory_reserved() / 1024**2
|
|
)
|
|
|
|
st.write(
|
|
f"**GPU Memory Allocated:** {allocated:.2f} MB"
|
|
)
|
|
|
|
st.write(
|
|
f"**GPU Memory Reserved:** {reserved:.2f} MB"
|
|
)
|
|
|
|
st.caption(
|
|
"Note: This is a zero-shot detection demonstration. "
|
|
"Formal precision and recall require manually labelled "
|
|
"ground-truth bounding boxes."
|
|
)
|