Initial commit
@@ -0,0 +1,26 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Virtual Environments (DO NOT COMMIT - ~7.9 GB!)
|
||||
**/venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
.env
|
||||
.venv
|
||||
|
||||
# Model Weights & Large Checkpoints
|
||||
# Uncomment if NOT using Git LFS:
|
||||
# *.pt
|
||||
# *.pth
|
||||
# *.bin
|
||||
# *.safetensors
|
||||
# **/weights/
|
||||
|
||||
# OS and Editor files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,146 @@
|
||||
# Open-Vocabulary Object Detection
|
||||
|
||||
## 1. Project Overview
|
||||
|
||||
This project implements an Open-Vocabulary Object Detection application using two pretrained models:
|
||||
|
||||
- Grounding DINO
|
||||
- YOLO-World
|
||||
|
||||
The application allows users to detect objects in images and videos using custom text prompts without requiring task-specific model training.
|
||||
|
||||
## 2. Features
|
||||
|
||||
- Image-based object detection
|
||||
- Video-based object detection
|
||||
- Custom text prompts
|
||||
- Bounding box visualization
|
||||
- Confidence score display
|
||||
- Object counting by category
|
||||
- Comparison between Grounding DINO and YOLO-World
|
||||
- CPU, RAM, GPU and VRAM monitoring
|
||||
- Annotated image and video outputs
|
||||
|
||||
## 3. Technologies Used
|
||||
|
||||
- Python
|
||||
- PyTorch
|
||||
- Grounding DINO
|
||||
- YOLO-World
|
||||
- Ultralytics
|
||||
- OpenCV
|
||||
- Streamlit
|
||||
- Transformers
|
||||
- NumPy
|
||||
- Pandas
|
||||
- Pillow
|
||||
- Matplotlib
|
||||
- psutil
|
||||
|
||||
## 4. Hardware Requirements
|
||||
|
||||
The application was developed and tested on a Linux-based system with an NVIDIA GPU.
|
||||
|
||||
Recommended requirements:
|
||||
|
||||
- NVIDIA GPU with CUDA support
|
||||
- 8 GB or more system RAM
|
||||
- Python 3.10 or later
|
||||
- Linux operating system
|
||||
- Internet connection for initial model downloads
|
||||
|
||||
Actual performance depends on hardware specifications and model configuration.
|
||||
|
||||
## 5. Installation
|
||||
|
||||
Clone or copy the project folder to your system.
|
||||
|
||||
Open a terminal inside the project directory.
|
||||
|
||||
Create a virtual environment:
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
```
|
||||
|
||||
Activate it:
|
||||
|
||||
```bash
|
||||
source venv/bin/activate
|
||||
```
|
||||
|
||||
Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install --upgrade pip
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## 6. Running the Application
|
||||
|
||||
Start the application using:
|
||||
|
||||
```bash
|
||||
streamlit run app.py
|
||||
```
|
||||
|
||||
The application will open in your web browser.
|
||||
|
||||
## 7. How to Use
|
||||
|
||||
1. Open the application.
|
||||
2. Select image or video input.
|
||||
3. Upload the required file.
|
||||
4. Select the detection model.
|
||||
5. Enter the object names as text prompts.
|
||||
6. Set the confidence threshold.
|
||||
7. Run detection.
|
||||
8. View the annotated output and detection results.
|
||||
9. Save the output for further analysis.
|
||||
|
||||
## 8. Model Comparison
|
||||
|
||||
The project evaluates Grounding DINO and YOLO-World based on:
|
||||
|
||||
- Inference time
|
||||
- Processing FPS
|
||||
- Detection count
|
||||
- Category detection performance
|
||||
- CPU utilization
|
||||
- RAM consumption
|
||||
- GPU utilization
|
||||
- VRAM consumption
|
||||
|
||||
Experimental measurements are stored in CSV files.
|
||||
|
||||
## 9. Project Structure
|
||||
|
||||
```text
|
||||
OpenVocabularyDetection/
|
||||
├── app.py
|
||||
├── monitor.py
|
||||
├── requirements.txt
|
||||
├── README.md
|
||||
├── benchmark.csv
|
||||
├── category_results.csv
|
||||
├── video_result.csv
|
||||
├── test_images/
|
||||
├── category_test_images/
|
||||
├── outputs/
|
||||
│ ├── grounding_dino/
|
||||
│ └── yolo_world/
|
||||
└── reports/
|
||||
```
|
||||
|
||||
## 10. Limitations
|
||||
|
||||
- Detection performance depends on the selected text prompt and confidence threshold.
|
||||
- Detection results may vary depending on image quality and lighting conditions.
|
||||
- Processing speed depends on available hardware.
|
||||
- Formal precision, recall and mAP evaluation requires ground-truth annotations.
|
||||
|
||||
## 11. Conclusion
|
||||
|
||||
This project demonstrates the use of pretrained open-vocabulary object detection models for detecting objects in images and videos using natural-language prompts.
|
||||
|
||||
Grounding DINO and YOLO-World were experimentally compared in terms of detection performance, inference speed and hardware resource consumption.
|
||||
@@ -0,0 +1,695 @@
|
||||
|
||||
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."
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
Image,Model,Prompt,Inference_Time_ms,Detection_Count,Detected_Labels,CPU_Percent,RAM_MB,GPU_Percent,VRAM_MB
|
||||
"Image 1","Grounding DINO","person, car, motorcycle, bus, truck, bicycle","955.25","13","person, bicycle","8.8%","6676","0%","2481"
|
||||
"Image 1","YOLO-World","person, car, motorcycle, bus, truck, bicycle","154.91","3","bicycle, person","26.3%","7544","0%","2485"
|
||||
"Image 2","Grounding DINO","person, car, motorcycle, bus, truck, bicycle","488.64","45","car, person, bicycle, truck, motorcycle, bus","6.5%","7398","100%","3161"
|
||||
"Image 2","YOLO-World","person, car, motorcycle, bus, truck, bicycle","108.22","14","person, car, bus, bicycle, truck","17%","7901","0%","3161"
|
||||
"Image 3","Grounding DINO","car, person, truck, bottle","356.75","10","bottle, person, car","9.5%","7108","3%","3165"
|
||||
"Image 3","YOLO-World","car, person truck, bottle","157.47","3","bottle, car","20.4%","7826","0%","3165"
|
||||
"Image 4","Grounding DINO","Excavator, Crane, Person, Hard hat, Traffic cone, Concrete mixer","361.77","24","person, hard hat, excavator, concrete mixer","9.7%","7635","0%","3165"
|
||||
"Image 4","YOLO-World","Excavator, Crane, Person, Hard hat, Traffic cone, Concrete mixer","114.15","14","Person, Hard Hat, Excavator","24.9%","8442","0%","3165"
|
||||
|
@@ -0,0 +1,343 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Ground-truth annotation + evaluation for Grounding DINO and YOLO-World.
|
||||
|
||||
Run from the Open_Vocabulary project directory:
|
||||
source venv/bin/activate
|
||||
python evaluate_models.py
|
||||
|
||||
The script opens each original image and asks you to draw one ground-truth
|
||||
box per listed target. Press ENTER/SPACE to accept each box. Press C to cancel
|
||||
and retry. The script then runs both models and writes evaluation CSV files.
|
||||
"""
|
||||
import csv
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
|
||||
from ultralytics import YOLOWorld
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
IMAGE_DIR = ROOT / "sample_images" / "Original_Images"
|
||||
ANNOTATION_FILE = ROOT / "reports" / "ground_truth_annotations.json"
|
||||
RESULTS_DIR = ROOT / "reports" / "evaluation"
|
||||
DINO_ID = "IDEA-Research/grounding-dino-tiny"
|
||||
YOLO_WEIGHTS = ROOT / "yolov8s-world.pt"
|
||||
CLASSES_BY_IMAGE = {
|
||||
"sample_1.png": ["person", "safety helmet"],
|
||||
"sample_2.png": ["safety helmet"],
|
||||
"sample_3.png": ["mobile phone"],
|
||||
"sample_4.png": ["laptop"],
|
||||
"sample_5.png": ["traffic cone"],
|
||||
"sample_6.png": ["caliper"],
|
||||
"sample_7.png": ["pipe wrench"],
|
||||
"sample_8.png": ["soldering iron"],
|
||||
}
|
||||
CLASSES = sorted({c for labels in CLASSES_BY_IMAGE.values() for c in labels})
|
||||
EVAL_CONFIDENCE = 0.25
|
||||
IOU_THRESHOLDS = [round(x, 2) for x in np.arange(0.50, 0.96, 0.05)]
|
||||
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
|
||||
def annotate_ground_truth():
|
||||
"""Create boxes using OpenCV's interactive ROI selector."""
|
||||
annotations = {}
|
||||
print("\nGROUND-TRUTH ANNOTATION")
|
||||
print("For each displayed target, drag a tight rectangle around the object.")
|
||||
print("Press ENTER/SPACE to accept the box; C cancels the current selection.\n")
|
||||
|
||||
for filename, labels in CLASSES_BY_IMAGE.items():
|
||||
path = IMAGE_DIR / filename
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Missing image: {path}")
|
||||
image = cv2.imread(str(path))
|
||||
if image is None:
|
||||
raise RuntimeError(f"Could not read image: {path}")
|
||||
|
||||
h, w = image.shape[:2]
|
||||
image_annotations = []
|
||||
for label in labels:
|
||||
display = image.copy()
|
||||
cv2.putText(
|
||||
display, f"{filename}: select the {label}",
|
||||
(5, 18), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 1,
|
||||
cv2.LINE_AA
|
||||
)
|
||||
print(f"{filename}: draw a box around '{label}' ({w}x{h})")
|
||||
while True:
|
||||
x, y, bw, bh = cv2.selectROI(
|
||||
"Ground Truth Annotation", display,
|
||||
showCrosshair=True, fromCenter=False
|
||||
)
|
||||
if bw > 0 and bh > 0:
|
||||
break
|
||||
print("No box selected. Please select the object.")
|
||||
x1, y1 = int(x), int(y)
|
||||
x2, y2 = int(x + bw), int(y + bh)
|
||||
image_annotations.append({
|
||||
"class": label,
|
||||
"bbox_xyxy": [x1, y1, x2, y2]
|
||||
})
|
||||
cv2.rectangle(display, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
||||
annotations[filename] = {
|
||||
"width": w, "height": h, "objects": image_annotations
|
||||
}
|
||||
print(f" Saved {len(image_annotations)} box(es) for {filename}")
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
ANNOTATION_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
ANNOTATION_FILE.write_text(json.dumps(annotations, indent=2))
|
||||
print(f"\nGround truth saved to: {ANNOTATION_FILE}")
|
||||
return annotations
|
||||
|
||||
|
||||
def load_annotations():
|
||||
if ANNOTATION_FILE.exists():
|
||||
answer = input(
|
||||
f"Existing annotations found at {ANNOTATION_FILE}.\n"
|
||||
"Reuse them? [Y/n]: "
|
||||
).strip().lower()
|
||||
if answer in ("", "y", "yes"):
|
||||
return json.loads(ANNOTATION_FILE.read_text())
|
||||
return annotate_ground_truth()
|
||||
|
||||
|
||||
def normalize_label(label):
|
||||
return " ".join(str(label).lower().replace("_", " ").replace("-", " ").split())
|
||||
|
||||
|
||||
def run_dino(image, labels, processor, model):
|
||||
prompt = ". ".join(labels) + "."
|
||||
inputs = processor(images=image, text=prompt, return_tensors="pt").to(DEVICE)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
start = time.perf_counter()
|
||||
with torch.inference_mode():
|
||||
outputs = model(**inputs)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
result = processor.post_process_grounded_object_detection(
|
||||
outputs, inputs.input_ids,
|
||||
threshold=0.001,
|
||||
text_threshold=0.25,
|
||||
target_sizes=[(image.height, image.width)]
|
||||
)[0]
|
||||
labels_out = result.get("text_labels", result.get("labels", []))
|
||||
detections = []
|
||||
for box, score, label in zip(result["boxes"], result["scores"], labels_out):
|
||||
detections.append({
|
||||
"class": normalize_label(label),
|
||||
"confidence": float(score),
|
||||
"bbox_xyxy": [float(v) for v in box.tolist()]
|
||||
})
|
||||
return detections, elapsed_ms
|
||||
|
||||
|
||||
def run_yolo(image, labels, model):
|
||||
model.set_classes(labels)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
start = time.perf_counter()
|
||||
results = model.predict(
|
||||
source=image, device=0 if DEVICE == "cuda" else "cpu",
|
||||
conf=0.001, imgsz=640, verbose=False
|
||||
)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
result = results[0]
|
||||
detections = []
|
||||
if result.boxes is not None:
|
||||
for box in result.boxes:
|
||||
class_id = int(box.cls[0])
|
||||
detections.append({
|
||||
"class": normalize_label(result.names[class_id]),
|
||||
"confidence": float(box.conf[0]),
|
||||
"bbox_xyxy": [float(v) for v in box.xyxy[0].tolist()]
|
||||
})
|
||||
return detections, elapsed_ms
|
||||
|
||||
|
||||
def iou_xyxy(a, b):
|
||||
x1 = max(a[0], b[0])
|
||||
y1 = max(a[1], b[1])
|
||||
x2 = min(a[2], b[2])
|
||||
y2 = min(a[3], b[3])
|
||||
inter = max(0.0, x2 - x1) * max(0.0, y2 - y1)
|
||||
area_a = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
|
||||
area_b = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
|
||||
union = area_a + area_b - inter
|
||||
return inter / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def evaluate_at_iou(predictions, annotations, class_name, iou_threshold):
|
||||
gt_by_image = {}
|
||||
total_gt = 0
|
||||
for filename, data in annotations.items():
|
||||
boxes = [
|
||||
obj["bbox_xyxy"] for obj in data["objects"]
|
||||
if normalize_label(obj["class"]) == class_name
|
||||
]
|
||||
gt_by_image[filename] = boxes
|
||||
total_gt += len(boxes)
|
||||
|
||||
preds = []
|
||||
for filename, detections in predictions.items():
|
||||
for det in detections:
|
||||
if normalize_label(det["class"]) == class_name and det["confidence"] >= EVAL_CONFIDENCE:
|
||||
preds.append((det["confidence"], filename, det["bbox_xyxy"]))
|
||||
preds.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
matched = {filename: set() for filename in gt_by_image}
|
||||
tp_flags, fp_flags = [], []
|
||||
tp = 0
|
||||
for confidence, filename, box in preds:
|
||||
candidates = gt_by_image.get(filename, [])
|
||||
best_iou, best_idx = 0.0, -1
|
||||
for idx, gt_box in enumerate(candidates):
|
||||
if idx in matched[filename]:
|
||||
continue
|
||||
overlap = iou_xyxy(box, gt_box)
|
||||
if overlap > best_iou:
|
||||
best_iou, best_idx = overlap, idx
|
||||
if best_idx >= 0 and best_iou >= iou_threshold:
|
||||
matched[filename].add(best_idx)
|
||||
tp += 1
|
||||
tp_flags.append(1)
|
||||
fp_flags.append(0)
|
||||
else:
|
||||
tp_flags.append(0)
|
||||
fp_flags.append(1)
|
||||
|
||||
fp = len(preds) - tp
|
||||
fn = total_gt - tp
|
||||
precision = tp / (tp + fp) if tp + fp else 0.0
|
||||
recall = tp / total_gt if total_gt else 0.0
|
||||
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
|
||||
|
||||
# 101-point interpolated AP; no-GT classes are excluded from mAP.
|
||||
ap = None
|
||||
if total_gt:
|
||||
if preds:
|
||||
tp_cum = np.cumsum(tp_flags)
|
||||
fp_cum = np.cumsum(fp_flags)
|
||||
recalls = tp_cum / total_gt
|
||||
precisions = tp_cum / np.maximum(tp_cum + fp_cum, 1)
|
||||
interpolated = []
|
||||
for recall_level in np.linspace(0, 1, 101):
|
||||
valid = precisions[recalls >= recall_level]
|
||||
interpolated.append(float(valid.max()) if len(valid) else 0.0)
|
||||
ap = float(np.mean(interpolated))
|
||||
else:
|
||||
ap = 0.0
|
||||
return {
|
||||
"TP": tp, "FP": fp, "FN": fn,
|
||||
"Precision": precision, "Recall": recall, "F1": f1, "AP": ap
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if not IMAGE_DIR.exists():
|
||||
raise FileNotFoundError(f"Image folder not found: {IMAGE_DIR}")
|
||||
annotations = load_annotations()
|
||||
|
||||
print(f"\nDevice: {DEVICE}")
|
||||
if DEVICE == "cuda":
|
||||
print(f"GPU: {torch.cuda.get_device_name(0)}")
|
||||
print("Loading Grounding DINO...")
|
||||
processor = AutoProcessor.from_pretrained(DINO_ID)
|
||||
dino = AutoModelForZeroShotObjectDetection.from_pretrained(DINO_ID).to(DEVICE)
|
||||
dino.eval()
|
||||
|
||||
print("Loading YOLO-World...")
|
||||
yolo = YOLOWorld(str(YOLO_WEIGHTS) if YOLO_WEIGHTS.exists() else "yolov8s-world.pt")
|
||||
|
||||
all_predictions = {"Grounding DINO": {}, "YOLO-World": {}}
|
||||
timing_rows = []
|
||||
labels = CLASSES
|
||||
|
||||
for filename in CLASSES_BY_IMAGE:
|
||||
image = Image.open(IMAGE_DIR / filename).convert("RGB")
|
||||
print(f"\nEvaluating {filename}...")
|
||||
dino_preds, dino_ms = run_dino(image, labels, processor, dino)
|
||||
yolo_preds, yolo_ms = run_yolo(image, labels, yolo)
|
||||
all_predictions["Grounding DINO"][filename] = dino_preds
|
||||
all_predictions["YOLO-World"][filename] = yolo_preds
|
||||
timing_rows.extend([
|
||||
{"Image": filename, "Model": "Grounding DINO",
|
||||
"Inference_Time_ms": round(dino_ms, 2),
|
||||
"Predictions_at_0.25": sum(p["confidence"] >= EVAL_CONFIDENCE for p in dino_preds)},
|
||||
{"Image": filename, "Model": "YOLO-World",
|
||||
"Inference_Time_ms": round(yolo_ms, 2),
|
||||
"Predictions_at_0.25": sum(p["confidence"] >= EVAL_CONFIDENCE for p in yolo_preds)}
|
||||
])
|
||||
print(f" Grounding DINO: {len(dino_preds)} raw predictions; {dino_ms:.1f} ms")
|
||||
print(f" YOLO-World: {len(yolo_preds)} raw predictions; {yolo_ms:.1f} ms")
|
||||
|
||||
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with (RESULTS_DIR / "inference_timings.csv").open("w", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=timing_rows[0].keys())
|
||||
writer.writeheader()
|
||||
writer.writerows(timing_rows)
|
||||
|
||||
summary_rows = []
|
||||
ap_rows = []
|
||||
for model_name, predictions in all_predictions.items():
|
||||
for class_name in CLASSES:
|
||||
base = evaluate_at_iou(predictions, annotations, class_name, 0.50)
|
||||
summary_rows.append({
|
||||
"Model": model_name, "Class": class_name,
|
||||
"IoU_Threshold": 0.50,
|
||||
**{k: round(v, 4) if isinstance(v, float) else v
|
||||
for k, v in base.items() if k != "AP"}
|
||||
})
|
||||
for threshold in IOU_THRESHOLDS:
|
||||
result = evaluate_at_iou(predictions, annotations, class_name, threshold)
|
||||
ap_rows.append({
|
||||
"Model": model_name, "Class": class_name,
|
||||
"IoU_Threshold": threshold,
|
||||
"AP": round(result["AP"], 4) if result["AP"] is not None else ""
|
||||
})
|
||||
|
||||
with (RESULTS_DIR / "metrics_by_class.csv").open("w", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=summary_rows[0].keys())
|
||||
writer.writeheader()
|
||||
writer.writerows(summary_rows)
|
||||
with (RESULTS_DIR / "average_precision.csv").open("w", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=ap_rows[0].keys())
|
||||
writer.writeheader()
|
||||
writer.writerows(ap_rows)
|
||||
|
||||
print("\nEVALUATION SUMMARY (confidence >= 0.25, IoU >= 0.50)")
|
||||
print(f"{'Model':<18} {'Precision':>11} {'Recall':>9} {'F1':>9}")
|
||||
for model_name in all_predictions:
|
||||
rows = [r for r in summary_rows if r["Model"] == model_name]
|
||||
tp = sum(r["TP"] for r in rows)
|
||||
fp = sum(r["FP"] for r in rows)
|
||||
fn = sum(r["FN"] for r in rows)
|
||||
p = tp / (tp + fp) if tp + fp else 0.0
|
||||
r = tp / (tp + fn) if tp + fn else 0.0
|
||||
f1 = 2*p*r/(p+r) if p+r else 0.0
|
||||
aps50 = [x["AP"] for x in ap_rows if x["Model"] == model_name and x["IoU_Threshold"] == 0.50 and x["AP"] != ""]
|
||||
all_aps = [x["AP"] for x in ap_rows if x["Model"] == model_name and x["AP"] != ""]
|
||||
map50 = float(np.mean(aps50)) if aps50 else 0.0
|
||||
map5095 = float(np.mean(all_aps)) if all_aps else 0.0
|
||||
print(f"{model_name:<18} {p:>11.4f} {r:>9.4f} {f1:>9.4f}")
|
||||
print(f" mAP@50={map50:.4f} | mAP@50:95={map5095:.4f}")
|
||||
|
||||
print("\nFiles saved in:", RESULTS_DIR)
|
||||
print(" ground_truth_annotations.json")
|
||||
print(" inference_timings.csv")
|
||||
print(" metrics_by_class.csv")
|
||||
print(" average_precision.csv")
|
||||
print("\nImportant: results are for this small 8-image dataset only.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,28 @@
|
||||
import psutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
print("Monitoring system usage. Press Ctrl+C to stop.\n")
|
||||
|
||||
try:
|
||||
while True:
|
||||
cpu = psutil.cpu_percent(interval=1)
|
||||
ram = psutil.virtual_memory().used / (1024 * 1024)
|
||||
|
||||
result = subprocess.check_output([
|
||||
"nvidia-smi",
|
||||
"--query-gpu=utilization.gpu,memory.used",
|
||||
"--format=csv,noheader,nounits"
|
||||
], text=True).strip()
|
||||
|
||||
gpu, vram = result.split(",")
|
||||
|
||||
print(
|
||||
f"CPU: {cpu:5.1f}% | "
|
||||
f"RAM: {ram:7.0f} MB | "
|
||||
f"GPU: {gpu.strip():>3}% | "
|
||||
f"VRAM: {vram.strip():>5} MB"
|
||||
)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\nMonitoring stopped.")
|
||||
|
After Width: | Height: | Size: 1.0 MiB |
|
After Width: | Height: | Size: 417 KiB |
|
After Width: | Height: | Size: 197 KiB |
|
After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 1.0 MiB |
|
After Width: | Height: | Size: 400 KiB |
|
After Width: | Height: | Size: 194 KiB |
|
After Width: | Height: | Size: 208 KiB |
@@ -0,0 +1,16 @@
|
||||
flowchart TD
|
||||
A[Image or Video Input] --> B[Streamlit Application]
|
||||
B --> C[Custom Text Prompt and Confidence Threshold]
|
||||
C --> D{Select Detection Model}
|
||||
D --> E[Grounding DINO]
|
||||
D --> F[YOLO-World]
|
||||
E --> G[Object Detection Processing]
|
||||
F --> G
|
||||
G --> H[Bounding Boxes and Confidence Scores]
|
||||
H --> I[Object Labels and Counts]
|
||||
I --> J[Annotated Image or Video Output]
|
||||
J --> K[Performance Evaluation]
|
||||
K --> L[CPU RAM GPU and VRAM]
|
||||
K --> M[Inference Time and FPS]
|
||||
L --> N[CSV Benchmark Results]
|
||||
M --> N
|
||||
|
After Width: | Height: | Size: 106 KiB |
@@ -0,0 +1,350 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Ground-truth annotation + evaluation for Grounding DINO and YOLO-World.
|
||||
|
||||
Run from the Open_Vocabulary project directory:
|
||||
source venv/bin/activate
|
||||
python evaluate_models.py
|
||||
|
||||
The script opens each original image and asks you to draw one ground-truth
|
||||
box per listed target. Press ENTER/SPACE to accept each box. Press C to cancel
|
||||
and retry. The script then runs both models and writes evaluation CSV files.
|
||||
"""
|
||||
import csv
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
|
||||
from ultralytics import YOLOWorld
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ROOT = SCRIPT_DIR.parent if SCRIPT_DIR.name == "reports" else SCRIPT_DIR
|
||||
IMAGE_DIR = ROOT / "sample_images" / "Original_Images"
|
||||
ANNOTATION_FILE = ROOT / "reports" / "ground_truth_annotations.json"
|
||||
RESULTS_DIR = ROOT / "reports" / "evaluation"
|
||||
DINO_ID = "IDEA-Research/grounding-dino-tiny"
|
||||
YOLO_WEIGHTS = ROOT / "yolov8s-world.pt"
|
||||
CLASSES_BY_IMAGE = {
|
||||
"sample_1.png": ["person", "safety helmet"],
|
||||
"sample_2.png": ["safety helmet"],
|
||||
"sample_3.png": ["mobile phone"],
|
||||
"sample_4.png": ["laptop"],
|
||||
"sample_5.png": ["traffic cone"],
|
||||
"sample_6.png": ["caliper"],
|
||||
"sample_7.png": ["pipe wrench"],
|
||||
"sample_8.png": ["soldering iron"],
|
||||
}
|
||||
CLASSES = sorted({c for labels in CLASSES_BY_IMAGE.values() for c in labels})
|
||||
EVAL_CONFIDENCE = 0.25
|
||||
IOU_THRESHOLDS = [round(x, 2) for x in np.arange(0.50, 0.96, 0.05)]
|
||||
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
|
||||
def annotate_ground_truth():
|
||||
"""Create boxes using OpenCV's interactive ROI selector."""
|
||||
annotations = {}
|
||||
print("\nGROUND-TRUTH ANNOTATION")
|
||||
print("For each displayed target, drag a tight rectangle around the object.")
|
||||
print("Press ENTER/SPACE to accept the box; C cancels the current selection.\n")
|
||||
|
||||
for filename, labels in CLASSES_BY_IMAGE.items():
|
||||
path = IMAGE_DIR / filename
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Missing image: {path}")
|
||||
image = cv2.imread(str(path))
|
||||
if image is None:
|
||||
raise RuntimeError(f"Could not read image: {path}")
|
||||
|
||||
h, w = image.shape[:2]
|
||||
image_annotations = []
|
||||
for label in labels:
|
||||
display = image.copy()
|
||||
cv2.putText(
|
||||
display, f"{filename}: select the {label}",
|
||||
(5, 18), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 1,
|
||||
cv2.LINE_AA
|
||||
)
|
||||
print(f"{filename}: draw a box around '{label}' ({w}x{h})")
|
||||
while True:
|
||||
x, y, bw, bh = cv2.selectROI(
|
||||
"Ground Truth Annotation", display,
|
||||
showCrosshair=True, fromCenter=False
|
||||
)
|
||||
if bw > 0 and bh > 0:
|
||||
break
|
||||
print("No box selected. Please select the object.")
|
||||
x1, y1 = int(x), int(y)
|
||||
x2, y2 = int(x + bw), int(y + bh)
|
||||
image_annotations.append({
|
||||
"class": label,
|
||||
"bbox_xyxy": [x1, y1, x2, y2]
|
||||
})
|
||||
cv2.rectangle(display, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
||||
annotations[filename] = {
|
||||
"width": w, "height": h, "objects": image_annotations
|
||||
}
|
||||
print(f" Saved {len(image_annotations)} box(es) for {filename}")
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
ANNOTATION_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
ANNOTATION_FILE.write_text(json.dumps(annotations, indent=2))
|
||||
print(f"\nGround truth saved to: {ANNOTATION_FILE}")
|
||||
return annotations
|
||||
|
||||
|
||||
def load_annotations():
|
||||
if ANNOTATION_FILE.exists():
|
||||
answer = input(
|
||||
f"Existing annotations found at {ANNOTATION_FILE}.\n"
|
||||
"Reuse them? [Y/n]: "
|
||||
).strip().lower()
|
||||
if answer in ("", "y", "yes"):
|
||||
return json.loads(ANNOTATION_FILE.read_text())
|
||||
return annotate_ground_truth()
|
||||
|
||||
|
||||
def normalize_label(label):
|
||||
return " ".join(str(label).lower().replace("_", " ").replace("-", " ").split())
|
||||
|
||||
|
||||
def run_dino(image, labels, processor, model):
|
||||
prompt = ". ".join(labels) + "."
|
||||
inputs = processor(images=image, text=prompt, return_tensors="pt").to(DEVICE)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
start = time.perf_counter()
|
||||
with torch.inference_mode():
|
||||
outputs = model(**inputs)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
result = processor.post_process_grounded_object_detection(
|
||||
outputs, inputs.input_ids,
|
||||
threshold=0.001,
|
||||
text_threshold=0.25,
|
||||
target_sizes=[(image.height, image.width)]
|
||||
)[0]
|
||||
labels_out = result.get("text_labels", result.get("labels", []))
|
||||
detections = []
|
||||
for box, score, label in zip(result["boxes"], result["scores"], labels_out):
|
||||
detections.append({
|
||||
"class": normalize_label(label),
|
||||
"confidence": float(score),
|
||||
"bbox_xyxy": [float(v) for v in box.tolist()]
|
||||
})
|
||||
return detections, elapsed_ms
|
||||
|
||||
|
||||
def run_yolo(image, labels, model):
|
||||
model.set_classes(labels)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
start = time.perf_counter()
|
||||
results = model.predict(
|
||||
source=image, device=0 if DEVICE == "cuda" else "cpu",
|
||||
conf=0.001, imgsz=640, verbose=False
|
||||
)
|
||||
if DEVICE == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
result = results[0]
|
||||
detections = []
|
||||
if result.boxes is not None:
|
||||
for box in result.boxes:
|
||||
class_id = int(box.cls[0])
|
||||
detections.append({
|
||||
"class": normalize_label(result.names[class_id]),
|
||||
"confidence": float(box.conf[0]),
|
||||
"bbox_xyxy": [float(v) for v in box.xyxy[0].tolist()]
|
||||
})
|
||||
return detections, elapsed_ms
|
||||
|
||||
|
||||
def iou_xyxy(a, b):
|
||||
x1 = max(a[0], b[0])
|
||||
y1 = max(a[1], b[1])
|
||||
x2 = min(a[2], b[2])
|
||||
y2 = min(a[3], b[3])
|
||||
inter = max(0.0, x2 - x1) * max(0.0, y2 - y1)
|
||||
area_a = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
|
||||
area_b = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
|
||||
union = area_a + area_b - inter
|
||||
return inter / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def evaluate_at_iou(predictions, annotations, class_name, iou_threshold):
|
||||
gt_by_image = {}
|
||||
total_gt = 0
|
||||
for filename, data in annotations.items():
|
||||
boxes = [
|
||||
obj["bbox_xyxy"] for obj in data["objects"]
|
||||
if normalize_label(obj["class"]) == class_name
|
||||
]
|
||||
gt_by_image[filename] = boxes
|
||||
total_gt += len(boxes)
|
||||
|
||||
preds = []
|
||||
for filename, detections in predictions.items():
|
||||
for det in detections:
|
||||
if normalize_label(det["class"]) == class_name and det["confidence"] >= EVAL_CONFIDENCE:
|
||||
preds.append((det["confidence"], filename, det["bbox_xyxy"]))
|
||||
preds.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
matched = {filename: set() for filename in gt_by_image}
|
||||
tp_flags, fp_flags = [], []
|
||||
tp = 0
|
||||
for confidence, filename, box in preds:
|
||||
candidates = gt_by_image.get(filename, [])
|
||||
best_iou, best_idx = 0.0, -1
|
||||
for idx, gt_box in enumerate(candidates):
|
||||
if idx in matched[filename]:
|
||||
continue
|
||||
overlap = iou_xyxy(box, gt_box)
|
||||
if overlap > best_iou:
|
||||
best_iou, best_idx = overlap, idx
|
||||
if best_idx >= 0 and best_iou >= iou_threshold:
|
||||
matched[filename].add(best_idx)
|
||||
tp += 1
|
||||
tp_flags.append(1)
|
||||
fp_flags.append(0)
|
||||
else:
|
||||
tp_flags.append(0)
|
||||
fp_flags.append(1)
|
||||
|
||||
fp = len(preds) - tp
|
||||
fn = total_gt - tp
|
||||
precision = tp / (tp + fp) if tp + fp else 0.0
|
||||
recall = tp / total_gt if total_gt else 0.0
|
||||
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
|
||||
|
||||
# 101-point interpolated AP; no-GT classes are excluded from mAP.
|
||||
ap = None
|
||||
if total_gt:
|
||||
if preds:
|
||||
tp_cum = np.cumsum(tp_flags)
|
||||
fp_cum = np.cumsum(fp_flags)
|
||||
recalls = tp_cum / total_gt
|
||||
precisions = tp_cum / np.maximum(tp_cum + fp_cum, 1)
|
||||
interpolated = []
|
||||
for recall_level in np.linspace(0, 1, 101):
|
||||
valid = precisions[recalls >= recall_level]
|
||||
interpolated.append(float(valid.max()) if len(valid) else 0.0)
|
||||
ap = float(np.mean(interpolated))
|
||||
else:
|
||||
ap = 0.0
|
||||
return {
|
||||
"TP": tp, "FP": fp, "FN": fn,
|
||||
"Precision": precision, "Recall": recall, "F1": f1, "AP": ap
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if not IMAGE_DIR.exists():
|
||||
raise FileNotFoundError(f"Image folder not found: {IMAGE_DIR}")
|
||||
annotations = load_annotations()
|
||||
|
||||
print(f"\nDevice: {DEVICE}")
|
||||
if DEVICE == "cuda":
|
||||
print(f"GPU: {torch.cuda.get_device_name(0)}")
|
||||
print("Loading Grounding DINO...")
|
||||
processor = AutoProcessor.from_pretrained(DINO_ID)
|
||||
dino = AutoModelForZeroShotObjectDetection.from_pretrained(DINO_ID).to(DEVICE)
|
||||
dino.eval()
|
||||
|
||||
print("Loading YOLO-World...")
|
||||
yolo = YOLOWorld(str(YOLO_WEIGHTS) if YOLO_WEIGHTS.exists() else "yolov8s-world.pt")
|
||||
|
||||
all_predictions = {"Grounding DINO": {}, "YOLO-World": {}}
|
||||
timing_rows = []
|
||||
labels = CLASSES
|
||||
|
||||
for filename in CLASSES_BY_IMAGE:
|
||||
image = Image.open(IMAGE_DIR / filename).convert("RGB")
|
||||
print(f"\nEvaluating {filename}...")
|
||||
dino_preds, dino_ms = run_dino(image, labels, processor, dino)
|
||||
yolo_preds, yolo_ms = run_yolo(image, labels, yolo)
|
||||
all_predictions["Grounding DINO"][filename] = dino_preds
|
||||
all_predictions["YOLO-World"][filename] = yolo_preds
|
||||
timing_rows.extend([
|
||||
{"Image": filename, "Model": "Grounding DINO",
|
||||
"Inference_Time_ms": round(dino_ms, 2),
|
||||
"Predictions_at_0.25": sum(p["confidence"] >= EVAL_CONFIDENCE for p in dino_preds)},
|
||||
{"Image": filename, "Model": "YOLO-World",
|
||||
"Inference_Time_ms": round(yolo_ms, 2),
|
||||
"Predictions_at_0.25": sum(p["confidence"] >= EVAL_CONFIDENCE for p in yolo_preds)}
|
||||
])
|
||||
print(f" Grounding DINO: {len(dino_preds)} raw predictions; {dino_ms:.1f} ms")
|
||||
print(f" YOLO-World: {len(yolo_preds)} raw predictions; {yolo_ms:.1f} ms")
|
||||
|
||||
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
# Preserve every raw prediction (including boxes and confidence) so results
|
||||
# can be independently audited and re-evaluated without rerunning inference.
|
||||
(RESULTS_DIR / "raw_predictions.json").write_text(
|
||||
json.dumps(all_predictions, indent=2)
|
||||
)
|
||||
with (RESULTS_DIR / "inference_timings.csv").open("w", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=timing_rows[0].keys())
|
||||
writer.writeheader()
|
||||
writer.writerows(timing_rows)
|
||||
|
||||
summary_rows = []
|
||||
ap_rows = []
|
||||
for model_name, predictions in all_predictions.items():
|
||||
for class_name in CLASSES:
|
||||
base = evaluate_at_iou(predictions, annotations, class_name, 0.50)
|
||||
summary_rows.append({
|
||||
"Model": model_name, "Class": class_name,
|
||||
"IoU_Threshold": 0.50,
|
||||
**{k: round(v, 4) if isinstance(v, float) else v
|
||||
for k, v in base.items() if k != "AP"}
|
||||
})
|
||||
for threshold in IOU_THRESHOLDS:
|
||||
result = evaluate_at_iou(predictions, annotations, class_name, threshold)
|
||||
ap_rows.append({
|
||||
"Model": model_name, "Class": class_name,
|
||||
"IoU_Threshold": threshold,
|
||||
"AP": round(result["AP"], 4) if result["AP"] is not None else ""
|
||||
})
|
||||
|
||||
with (RESULTS_DIR / "metrics_by_class.csv").open("w", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=summary_rows[0].keys())
|
||||
writer.writeheader()
|
||||
writer.writerows(summary_rows)
|
||||
with (RESULTS_DIR / "average_precision.csv").open("w", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=ap_rows[0].keys())
|
||||
writer.writeheader()
|
||||
writer.writerows(ap_rows)
|
||||
|
||||
print("\nEVALUATION SUMMARY (confidence >= 0.25, IoU >= 0.50)")
|
||||
print(f"{'Model':<18} {'Precision':>11} {'Recall':>9} {'F1':>9}")
|
||||
for model_name in all_predictions:
|
||||
rows = [r for r in summary_rows if r["Model"] == model_name]
|
||||
tp = sum(r["TP"] for r in rows)
|
||||
fp = sum(r["FP"] for r in rows)
|
||||
fn = sum(r["FN"] for r in rows)
|
||||
p = tp / (tp + fp) if tp + fp else 0.0
|
||||
r = tp / (tp + fn) if tp + fn else 0.0
|
||||
f1 = 2*p*r/(p+r) if p+r else 0.0
|
||||
aps50 = [x["AP"] for x in ap_rows if x["Model"] == model_name and x["IoU_Threshold"] == 0.50 and x["AP"] != ""]
|
||||
all_aps = [x["AP"] for x in ap_rows if x["Model"] == model_name and x["AP"] != ""]
|
||||
map50 = float(np.mean(aps50)) if aps50 else 0.0
|
||||
map5095 = float(np.mean(all_aps)) if all_aps else 0.0
|
||||
print(f"{model_name:<18} {p:>11.4f} {r:>9.4f} {f1:>9.4f}")
|
||||
print(f" mAP@50={map50:.4f} | mAP@50:95={map5095:.4f}")
|
||||
|
||||
print("\nFiles saved in:", RESULTS_DIR)
|
||||
print(" ground_truth_annotations.json")
|
||||
print(" inference_timings.csv")
|
||||
print(" raw_predictions.json")
|
||||
print(" metrics_by_class.csv")
|
||||
print(" average_precision.csv")
|
||||
print("\nImportant: results are for this small 8-image dataset only.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,161 @@
|
||||
Model,Class,IoU_Threshold,AP
|
||||
Grounding DINO,caliper,0.5,0.0
|
||||
Grounding DINO,caliper,0.55,0.0
|
||||
Grounding DINO,caliper,0.6,0.0
|
||||
Grounding DINO,caliper,0.65,0.0
|
||||
Grounding DINO,caliper,0.7,0.0
|
||||
Grounding DINO,caliper,0.75,0.0
|
||||
Grounding DINO,caliper,0.8,0.0
|
||||
Grounding DINO,caliper,0.85,0.0
|
||||
Grounding DINO,caliper,0.9,0.0
|
||||
Grounding DINO,caliper,0.95,0.0
|
||||
Grounding DINO,laptop,0.5,1.0
|
||||
Grounding DINO,laptop,0.55,1.0
|
||||
Grounding DINO,laptop,0.6,1.0
|
||||
Grounding DINO,laptop,0.65,1.0
|
||||
Grounding DINO,laptop,0.7,0.0
|
||||
Grounding DINO,laptop,0.75,0.0
|
||||
Grounding DINO,laptop,0.8,0.0
|
||||
Grounding DINO,laptop,0.85,0.0
|
||||
Grounding DINO,laptop,0.9,0.0
|
||||
Grounding DINO,laptop,0.95,0.0
|
||||
Grounding DINO,mobile phone,0.5,1.0
|
||||
Grounding DINO,mobile phone,0.55,1.0
|
||||
Grounding DINO,mobile phone,0.6,0.0
|
||||
Grounding DINO,mobile phone,0.65,0.0
|
||||
Grounding DINO,mobile phone,0.7,0.0
|
||||
Grounding DINO,mobile phone,0.75,0.0
|
||||
Grounding DINO,mobile phone,0.8,0.0
|
||||
Grounding DINO,mobile phone,0.85,0.0
|
||||
Grounding DINO,mobile phone,0.9,0.0
|
||||
Grounding DINO,mobile phone,0.95,0.0
|
||||
Grounding DINO,person,0.5,1.0
|
||||
Grounding DINO,person,0.55,1.0
|
||||
Grounding DINO,person,0.6,1.0
|
||||
Grounding DINO,person,0.65,1.0
|
||||
Grounding DINO,person,0.7,1.0
|
||||
Grounding DINO,person,0.75,1.0
|
||||
Grounding DINO,person,0.8,1.0
|
||||
Grounding DINO,person,0.85,1.0
|
||||
Grounding DINO,person,0.9,0.0
|
||||
Grounding DINO,person,0.95,0.0
|
||||
Grounding DINO,pipe wrench,0.5,0.0
|
||||
Grounding DINO,pipe wrench,0.55,0.0
|
||||
Grounding DINO,pipe wrench,0.6,0.0
|
||||
Grounding DINO,pipe wrench,0.65,0.0
|
||||
Grounding DINO,pipe wrench,0.7,0.0
|
||||
Grounding DINO,pipe wrench,0.75,0.0
|
||||
Grounding DINO,pipe wrench,0.8,0.0
|
||||
Grounding DINO,pipe wrench,0.85,0.0
|
||||
Grounding DINO,pipe wrench,0.9,0.0
|
||||
Grounding DINO,pipe wrench,0.95,0.0
|
||||
Grounding DINO,safety helmet,0.5,0.2525
|
||||
Grounding DINO,safety helmet,0.55,0.2525
|
||||
Grounding DINO,safety helmet,0.6,0.2525
|
||||
Grounding DINO,safety helmet,0.65,0.2525
|
||||
Grounding DINO,safety helmet,0.7,0.2525
|
||||
Grounding DINO,safety helmet,0.75,0.2525
|
||||
Grounding DINO,safety helmet,0.8,0.2525
|
||||
Grounding DINO,safety helmet,0.85,0.0
|
||||
Grounding DINO,safety helmet,0.9,0.0
|
||||
Grounding DINO,safety helmet,0.95,0.0
|
||||
Grounding DINO,soldering iron,0.5,0.0
|
||||
Grounding DINO,soldering iron,0.55,0.0
|
||||
Grounding DINO,soldering iron,0.6,0.0
|
||||
Grounding DINO,soldering iron,0.65,0.0
|
||||
Grounding DINO,soldering iron,0.7,0.0
|
||||
Grounding DINO,soldering iron,0.75,0.0
|
||||
Grounding DINO,soldering iron,0.8,0.0
|
||||
Grounding DINO,soldering iron,0.85,0.0
|
||||
Grounding DINO,soldering iron,0.9,0.0
|
||||
Grounding DINO,soldering iron,0.95,0.0
|
||||
Grounding DINO,traffic cone,0.5,1.0
|
||||
Grounding DINO,traffic cone,0.55,1.0
|
||||
Grounding DINO,traffic cone,0.6,1.0
|
||||
Grounding DINO,traffic cone,0.65,1.0
|
||||
Grounding DINO,traffic cone,0.7,1.0
|
||||
Grounding DINO,traffic cone,0.75,0.0
|
||||
Grounding DINO,traffic cone,0.8,0.0
|
||||
Grounding DINO,traffic cone,0.85,0.0
|
||||
Grounding DINO,traffic cone,0.9,0.0
|
||||
Grounding DINO,traffic cone,0.95,0.0
|
||||
YOLO-World,caliper,0.5,0.0
|
||||
YOLO-World,caliper,0.55,0.0
|
||||
YOLO-World,caliper,0.6,0.0
|
||||
YOLO-World,caliper,0.65,0.0
|
||||
YOLO-World,caliper,0.7,0.0
|
||||
YOLO-World,caliper,0.75,0.0
|
||||
YOLO-World,caliper,0.8,0.0
|
||||
YOLO-World,caliper,0.85,0.0
|
||||
YOLO-World,caliper,0.9,0.0
|
||||
YOLO-World,caliper,0.95,0.0
|
||||
YOLO-World,laptop,0.5,1.0
|
||||
YOLO-World,laptop,0.55,1.0
|
||||
YOLO-World,laptop,0.6,1.0
|
||||
YOLO-World,laptop,0.65,1.0
|
||||
YOLO-World,laptop,0.7,0.0
|
||||
YOLO-World,laptop,0.75,0.0
|
||||
YOLO-World,laptop,0.8,0.0
|
||||
YOLO-World,laptop,0.85,0.0
|
||||
YOLO-World,laptop,0.9,0.0
|
||||
YOLO-World,laptop,0.95,0.0
|
||||
YOLO-World,mobile phone,0.5,1.0
|
||||
YOLO-World,mobile phone,0.55,1.0
|
||||
YOLO-World,mobile phone,0.6,0.0
|
||||
YOLO-World,mobile phone,0.65,0.0
|
||||
YOLO-World,mobile phone,0.7,0.0
|
||||
YOLO-World,mobile phone,0.75,0.0
|
||||
YOLO-World,mobile phone,0.8,0.0
|
||||
YOLO-World,mobile phone,0.85,0.0
|
||||
YOLO-World,mobile phone,0.9,0.0
|
||||
YOLO-World,mobile phone,0.95,0.0
|
||||
YOLO-World,person,0.5,1.0
|
||||
YOLO-World,person,0.55,1.0
|
||||
YOLO-World,person,0.6,1.0
|
||||
YOLO-World,person,0.65,1.0
|
||||
YOLO-World,person,0.7,1.0
|
||||
YOLO-World,person,0.75,1.0
|
||||
YOLO-World,person,0.8,1.0
|
||||
YOLO-World,person,0.85,1.0
|
||||
YOLO-World,person,0.9,0.0
|
||||
YOLO-World,person,0.95,0.0
|
||||
YOLO-World,pipe wrench,0.5,0.0
|
||||
YOLO-World,pipe wrench,0.55,0.0
|
||||
YOLO-World,pipe wrench,0.6,0.0
|
||||
YOLO-World,pipe wrench,0.65,0.0
|
||||
YOLO-World,pipe wrench,0.7,0.0
|
||||
YOLO-World,pipe wrench,0.75,0.0
|
||||
YOLO-World,pipe wrench,0.8,0.0
|
||||
YOLO-World,pipe wrench,0.85,0.0
|
||||
YOLO-World,pipe wrench,0.9,0.0
|
||||
YOLO-World,pipe wrench,0.95,0.0
|
||||
YOLO-World,safety helmet,0.5,0.0
|
||||
YOLO-World,safety helmet,0.55,0.0
|
||||
YOLO-World,safety helmet,0.6,0.0
|
||||
YOLO-World,safety helmet,0.65,0.0
|
||||
YOLO-World,safety helmet,0.7,0.0
|
||||
YOLO-World,safety helmet,0.75,0.0
|
||||
YOLO-World,safety helmet,0.8,0.0
|
||||
YOLO-World,safety helmet,0.85,0.0
|
||||
YOLO-World,safety helmet,0.9,0.0
|
||||
YOLO-World,safety helmet,0.95,0.0
|
||||
YOLO-World,soldering iron,0.5,0.0
|
||||
YOLO-World,soldering iron,0.55,0.0
|
||||
YOLO-World,soldering iron,0.6,0.0
|
||||
YOLO-World,soldering iron,0.65,0.0
|
||||
YOLO-World,soldering iron,0.7,0.0
|
||||
YOLO-World,soldering iron,0.75,0.0
|
||||
YOLO-World,soldering iron,0.8,0.0
|
||||
YOLO-World,soldering iron,0.85,0.0
|
||||
YOLO-World,soldering iron,0.9,0.0
|
||||
YOLO-World,soldering iron,0.95,0.0
|
||||
YOLO-World,traffic cone,0.5,1.0
|
||||
YOLO-World,traffic cone,0.55,1.0
|
||||
YOLO-World,traffic cone,0.6,1.0
|
||||
YOLO-World,traffic cone,0.65,1.0
|
||||
YOLO-World,traffic cone,0.7,1.0
|
||||
YOLO-World,traffic cone,0.75,0.0
|
||||
YOLO-World,traffic cone,0.8,0.0
|
||||
YOLO-World,traffic cone,0.85,0.0
|
||||
YOLO-World,traffic cone,0.9,0.0
|
||||
YOLO-World,traffic cone,0.95,0.0
|
||||
|
@@ -0,0 +1,17 @@
|
||||
Image,Model,Inference_Time_ms,Predictions_at_0.25
|
||||
sample_1.png,Grounding DINO,672.13,4
|
||||
sample_1.png,YOLO-World,114.76,2
|
||||
sample_2.png,Grounding DINO,357.13,3
|
||||
sample_2.png,YOLO-World,96.0,0
|
||||
sample_3.png,Grounding DINO,358.56,2
|
||||
sample_3.png,YOLO-World,70.42,2
|
||||
sample_4.png,Grounding DINO,346.23,5
|
||||
sample_4.png,YOLO-World,109.14,1
|
||||
sample_5.png,Grounding DINO,359.38,2
|
||||
sample_5.png,YOLO-World,72.02,2
|
||||
sample_6.png,Grounding DINO,366.9,4
|
||||
sample_6.png,YOLO-World,69.72,0
|
||||
sample_7.png,Grounding DINO,357.22,1
|
||||
sample_7.png,YOLO-World,71.54,0
|
||||
sample_8.png,Grounding DINO,373.23,7
|
||||
sample_8.png,YOLO-World,70.28,0
|
||||
|
@@ -0,0 +1,17 @@
|
||||
Model,Class,IoU_Threshold,TP,FP,FN,Precision,Recall,F1
|
||||
Grounding DINO,caliper,0.5,0,5,1,0.0,0.0,0.0
|
||||
Grounding DINO,laptop,0.5,1,0,0,1.0,1.0,1.0
|
||||
Grounding DINO,mobile phone,0.5,1,4,0,0.2,1.0,0.3333
|
||||
Grounding DINO,person,0.5,1,6,0,0.1429,1.0,0.25
|
||||
Grounding DINO,pipe wrench,0.5,0,0,1,0.0,0.0,0.0
|
||||
Grounding DINO,safety helmet,0.5,1,1,1,0.5,0.5,0.5
|
||||
Grounding DINO,soldering iron,0.5,0,1,1,0.0,0.0,0.0
|
||||
Grounding DINO,traffic cone,0.5,1,0,0,1.0,1.0,1.0
|
||||
YOLO-World,caliper,0.5,0,0,1,0.0,0.0,0.0
|
||||
YOLO-World,laptop,0.5,1,0,0,1.0,1.0,1.0
|
||||
YOLO-World,mobile phone,0.5,1,0,0,1.0,1.0,1.0
|
||||
YOLO-World,person,0.5,1,2,0,0.3333,1.0,0.5
|
||||
YOLO-World,pipe wrench,0.5,0,0,1,0.0,0.0,0.0
|
||||
YOLO-World,safety helmet,0.5,0,1,2,0.0,0.0,0.0
|
||||
YOLO-World,soldering iron,0.5,0,0,1,0.0,0.0,0.0
|
||||
YOLO-World,traffic cone,0.5,1,0,0,1.0,1.0,1.0
|
||||
|
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"sample_1.png": {
|
||||
"width": 162,
|
||||
"height": 182,
|
||||
"objects": [
|
||||
{
|
||||
"class": "person",
|
||||
"bbox_xyxy": [
|
||||
47,
|
||||
8,
|
||||
116,
|
||||
177
|
||||
]
|
||||
},
|
||||
{
|
||||
"class": "safety helmet",
|
||||
"bbox_xyxy": [
|
||||
79,
|
||||
13,
|
||||
101,
|
||||
36
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_2.png": {
|
||||
"width": 171,
|
||||
"height": 182,
|
||||
"objects": [
|
||||
{
|
||||
"class": "safety helmet",
|
||||
"bbox_xyxy": [
|
||||
10,
|
||||
9,
|
||||
161,
|
||||
147
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_3.png": {
|
||||
"width": 171,
|
||||
"height": 185,
|
||||
"objects": [
|
||||
{
|
||||
"class": "mobile phone",
|
||||
"bbox_xyxy": [
|
||||
42,
|
||||
7,
|
||||
146,
|
||||
174
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_4.png": {
|
||||
"width": 175,
|
||||
"height": 183,
|
||||
"objects": [
|
||||
{
|
||||
"class": "laptop",
|
||||
"bbox_xyxy": [
|
||||
2,
|
||||
19,
|
||||
174,
|
||||
169
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_5.png": {
|
||||
"width": 167,
|
||||
"height": 181,
|
||||
"objects": [
|
||||
{
|
||||
"class": "traffic cone",
|
||||
"bbox_xyxy": [
|
||||
36,
|
||||
26,
|
||||
132,
|
||||
179
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_6.png": {
|
||||
"width": 166,
|
||||
"height": 184,
|
||||
"objects": [
|
||||
{
|
||||
"class": "caliper",
|
||||
"bbox_xyxy": [
|
||||
22,
|
||||
33,
|
||||
164,
|
||||
153
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_7.png": {
|
||||
"width": 167,
|
||||
"height": 181,
|
||||
"objects": [
|
||||
{
|
||||
"class": "pipe wrench",
|
||||
"bbox_xyxy": [
|
||||
2,
|
||||
49,
|
||||
166,
|
||||
164
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"sample_8.png": {
|
||||
"width": 161,
|
||||
"height": 181,
|
||||
"objects": [
|
||||
{
|
||||
"class": "soldering iron",
|
||||
"bbox_xyxy": [
|
||||
52,
|
||||
0,
|
||||
160,
|
||||
124
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 54 KiB |
@@ -0,0 +1,13 @@
|
||||
|
||||
torch
|
||||
torchvision
|
||||
transformers
|
||||
accelerate
|
||||
ultralytics
|
||||
streamlit
|
||||
opencv-python
|
||||
Pillow
|
||||
pandas
|
||||
numpy
|
||||
matplotlib
|
||||
psutil
|
||||
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 54 KiB |
@@ -0,0 +1,17 @@
|
||||
Category,Image_Name,Model,Prompt,Confidence_Threshold,Detected,Detection_Count,Confidence_Score,Inference_Time_ms,CPU_Percent,RAM_MB,GPU_Percent,VRAM_MB
|
||||
"Person","sample_1.png","Grounding DINO","person","0.25","Yes","1","0.876","931.12","7.6%","8267","100%","3165"
|
||||
"Person","sample_1.png","YOLO-World","person","0.25","Yes","1","0.929","136.31","21.3%","7706","0%","365"
|
||||
"Safety helmet","sample_2.png","Grounding DINO","safety helmet","0.25","Yes","1","0.828","882.43","7.9%","8246","100%","3165"
|
||||
"Safety helmet","sample_2.png","YOLO-World","safety helmet","0.25","No","0","0.0","120.78","15.7%","9112","0%","3167"
|
||||
"Mobile phone","sample_3.png","Grounding DINO","mobile phone","0.25","Yes","1","0.924","895.64","6.2%","7009","100%","3167"
|
||||
"Mobile phone","sample_3.png","YOLO-World","mobile phone","0.25","Yes","1","0.73","132.04","17.3%","7999","0%","3167"
|
||||
"Laptop","sample_4.png","Grounding DINO","laptop","0.25","Yes","1","0.782","878.37","10.6%","7708","0%","3167"
|
||||
"Laptop","sample_4.png","YOLO-World","laptop","0.25","Yes","1","0.89","149.01","14.6%","8619","0%","3167"
|
||||
"Traffic cone","sample_5.png","Grounding DINO","traffic cone","0.25","Yes","1","0.894","896.65","7.0%","8324","100%","3167"
|
||||
"Traffic cone","sample_5.png","YOLO-World","traffic cone","0.25","No","0","0.0","135.87","16.6%","7839","0%","3167"
|
||||
"Caliper","sample_6.png","Grounding DINO","caliper","0.25","Yes","1","0.73","925.16","10.6%","8283","100%","3167"
|
||||
"Caliper","sample_6.png","YOLO-World","caliper","0.25","No","0","0.0","132.44","16.3%","8471","0%","3167"
|
||||
"Pipe wrench","sample_7.png","Grounding DINO","pipe wrench","0.25","Yes","1","0.782","891.96","10.0%","7178","25%","3167"
|
||||
"Pipe wrench","sample_7.png","YOLO-World","pipe wrench","0.25","No","0","0.0","131.30","16.0%","7877","0%","3167",
|
||||
"Soldering iron","sample_8.png","Grounding DINO","soldering iron","0.25","Yes","4","0.374","931.40","8.7%","7732","100%","3167"
|
||||
"Soldering iron","sample_8.png","YOLO-World","soldering iron","0.25","No","0","0.0","131.66","17.1%","8533","0%","3167"
|
||||
|
@@ -0,0 +1,3 @@
|
||||
Model,Video_Name,Duration_Seconds,Frames_Processed,Avg_Inference_Time_ms,FPS,Peak_CPU_Percent,Peak_RAM_MB,Peak_GPU_Percent,Peak_VRAM_MB,Total_Detections
|
||||
Grounding DINO,traffic.mp4,60,120,741.52,1.5,10.4%,7418,100%,3167,1784
|
||||
YOLO-World,traffic.mp4,60,120,79.10,13,26.4,9370,54%,3371,949
|
||||
|
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 474 KiB |
|
After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 257 KiB |