initial commit

This commit is contained in:
2026-11-25 15:45:36 +05:30
commit e6007d7b07
50 changed files with 3818 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""Detection pipelines: prompts, images, video and visualisation."""
+73
View File
@@ -0,0 +1,73 @@
"""Image detection pipeline (also usable from the command line)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
import numpy as np
from detection.prompt_manager import parse_prompts, require_prompts
from detection.visualization import draw_detections, save_annotated_image
from utils.config_loader import ensure_project_dirs, load_config
from utils.image_utils import load_image_rgb, resize_long_side, validate_extension
from utils.logger import get_logger
logger = get_logger("image_detection")
def run_image_detection(manager, model_name: str, image_rgb: np.ndarray, prompts: list[str],
device: str = "auto", conf: float | None = None,
text_threshold: float | None = None, max_side: int | None = None,
imgsz: int | None = None) -> dict:
"""Run one model on one image. Returned boxes are in ORIGINAL image coordinates.
The image may be downscaled for inference (max_side); boxes are mapped back afterwards.
"""
prompts = require_prompts(prompts)
cfg = load_config()["image"]
max_side = cfg["inference_max_side"] if max_side is None else max_side
orig_h, orig_w = image_rgb.shape[:2]
small, scale = resize_long_side(image_rgb, max_side)
result = manager.detect(model_name, small, prompts, device=device, conf=conf,
text_threshold=text_threshold, imgsz=imgsz)
if scale != 1.0:
result["boxes"] = [
[round(min(max(v / scale, 0.0), lim), 2) for v, lim in zip(box, (orig_w, orig_h, orig_w, orig_h))]
for box in result["boxes"]
]
result["image_width"], result["image_height"] = orig_w, orig_h
result["inference_scale"] = scale
result["prompts"] = prompts
return result
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Open-vocabulary detection on one image.")
parser.add_argument("--image", required=True, help="Path to the input image")
parser.add_argument("--model", default="Grounding DINO", help="'Grounding DINO' or 'YOLO-World'")
parser.add_argument("--prompts", required=True, help="Comma-separated categories, e.g. 'person, safety helmet'")
parser.add_argument("--device", default=load_config()["device"]["default"])
parser.add_argument("--conf", type=float, default=None, help="Confidence / box threshold")
parser.add_argument("--text-threshold", type=float, default=None)
parser.add_argument("--max-side", type=int, default=None)
args = parser.parse_args(argv)
from models.model_manager import ModelManager, normalize_model_name
ensure_project_dirs()
validate_extension(args.image, load_config()["image"]["allowed_extensions"])
image = load_image_rgb(args.image)
result = run_image_detection(ModelManager(), normalize_model_name(args.model), image,
parse_prompts(args.prompts), args.device, args.conf,
args.text_threshold, args.max_side)
out = save_annotated_image(draw_detections(image, result), stem=Path(args.image).stem)
print(json.dumps({k: v for k, v in result.items() if k != "prompts"}, indent=2))
print(f"\nAnnotated image saved to: {out}")
return 0
if __name__ == "__main__":
sys.exit(main())
+118
View File
@@ -0,0 +1,118 @@
"""Prompt (object category) parsing, per-model preparation and preset storage."""
from __future__ import annotations
import json
import re
from pathlib import Path
from utils.config_loader import load_config, resolve_path
class PromptError(ValueError):
"""Raised when no valid prompts remain after cleaning."""
def normalize_prompt(text: str) -> str:
"""Collapse whitespace and strip surrounding spaces/periods."""
return re.sub(r"\s+", " ", str(text)).strip().strip(".").strip()
def parse_prompts(raw: str | list[str]) -> list[str]:
"""Split comma/newline separated text (or a list) into a clean, de-duplicated list.
Order is preserved; duplicates are detected case-insensitively; empties are removed.
"""
if isinstance(raw, str):
parts = re.split(r"[,\n\r;]+", raw)
else:
parts = [piece for item in raw for piece in re.split(r"[\n\r;]+", str(item))]
seen: set[str] = set()
cleaned: list[str] = []
for part in parts:
norm = normalize_prompt(part)
if norm and norm.lower() not in seen:
seen.add(norm.lower())
cleaned.append(norm)
return cleaned
def require_prompts(prompts: list[str]) -> list[str]:
cleaned = parse_prompts(prompts)
if not cleaned:
raise PromptError("Please enter at least one object category.")
return cleaned
def prepare_for_grounding_dino(prompts: list[str]) -> str:
"""Grounding DINO expects ONE lower-case string with classes separated by periods."""
cleaned = require_prompts(prompts)
return " . ".join(p.lower() for p in cleaned) + " ."
def prepare_for_yolo_world(prompts: list[str]) -> list[str]:
"""YOLO-World's set_classes() expects a list of class names."""
return require_prompts(prompts)
def match_label_to_prompt(label: str, prompts: list[str]) -> str:
"""Map a (possibly partial/composite) Grounding DINO label back to one of the prompts."""
norm = normalize_prompt(label).lower()
lookup = {p.lower(): p for p in prompts}
if norm in lookup:
return lookup[norm]
candidates = [orig for low, orig in lookup.items() if low in norm or norm in low]
if candidates:
return max(candidates, key=len)
return norm
# ----------------------------------------------------------------- presets
def _prompts_dir() -> Path:
path = resolve_path(load_config()["paths"]["prompts_dir"])
path.mkdir(parents=True, exist_ok=True)
return path
def load_test_prompts() -> dict:
path = _prompts_dir() / "test_prompts.json"
if not path.exists():
return {"categories": [], "common": [], "uncommon": []}
with path.open("r", encoding="utf-8") as fh:
return json.load(fh)
def load_saved_presets() -> dict[str, list[str]]:
path = _prompts_dir() / "saved_prompts.json"
if not path.exists():
return {}
try:
with path.open("r", encoding="utf-8") as fh:
data = json.load(fh)
except (json.JSONDecodeError, OSError):
return {}
return {str(k): parse_prompts(v) for k, v in data.items() if isinstance(v, list)}
def save_prompt_preset(name: str, prompts: list[str]) -> None:
name = normalize_prompt(name)
if not name:
raise PromptError("Preset name cannot be empty.")
prompts = require_prompts(prompts)
presets = load_saved_presets()
presets[name] = prompts
with (_prompts_dir() / "saved_prompts.json").open("w", encoding="utf-8") as fh:
json.dump(presets, fh, indent=2, ensure_ascii=False)
def get_all_presets() -> dict[str, list[str]]:
"""Built-in test sets followed by the user's saved presets."""
test = load_test_prompts()
presets: dict[str, list[str]] = {}
if test.get("categories"):
presets[f"Test set - all {len(test['categories'])} categories"] = test["categories"]
if test.get("common"):
presets["Test set - common"] = test["common"]
if test.get("uncommon"):
presets["Test set - uncommon industrial"] = test["uncommon"]
presets.update(load_saved_presets())
return presets
+178
View File
@@ -0,0 +1,178 @@
"""Video detection pipeline (also usable from the command line)."""
from __future__ import annotations
import argparse
import json
import shutil
import sys
import time
from pathlib import Path
from typing import Callable
import cv2
import numpy as np
from detection.prompt_manager import parse_prompts, require_prompts
from detection.visualization import draw_detections
from utils.config_loader import ensure_project_dirs, load_config, resolve_path
from utils.image_utils import resize_long_side
from utils.logger import get_logger
from utils.video_utils import VideoError, create_video_writer, get_video_info, reencode_h264
logger = get_logger("video_detection")
def process_video(manager, model_name: str, input_path: str | Path, output_path: str | Path,
prompts: list[str], device: str = "auto", conf: float | None = None,
text_threshold: float | None = None, frame_skip: int | None = None,
resize_side: int | None = None, imgsz: int | None = None,
max_frames: int | None = None, warmup: bool | None = None,
progress_callback: Callable | None = None) -> dict:
"""Detect objects in every Nth frame, write an annotated video and return timing statistics.
Timing definitions
inference FPS = processed frames / summed MODEL inference time (forward + post-processing)
end-to-end FPS = processed frames / wall time of the whole loop (decode, resize, model,
drawing, encoding)
The input video's FPS is reported separately and is never used as a model FPS.
When frame_skip > 1 only every Nth frame is processed AND written; the output video is
written at input_fps / frame_skip so it still plays back at real-time speed.
"""
cfg = load_config()["video"]
frame_skip = max(1, int(cfg["frame_skip"] if frame_skip is None else frame_skip))
resize_side = cfg["resize_long_side"] if resize_side is None else resize_side
max_frames = cfg["max_frames"] if max_frames is None else max_frames
warmup = cfg["warmup"] if warmup is None else warmup
prompts = require_prompts(prompts)
input_path, output_path = Path(input_path), Path(output_path)
info = get_video_info(input_path)
cap = cv2.VideoCapture(str(input_path))
if not cap.isOpened():
raise VideoError(f"Cannot open video '{input_path.name}'.")
writer = None
codec_used = None
tmp_path = output_path.with_suffix(".tmp.mp4")
records: list[dict] = []
frame_idx = -1
processed = 0
try:
if warmup: # untimed warm-up on a blank frame of the working resolution
blank, _ = resize_long_side(np.full((info["height"] or 480, info["width"] or 640, 3), 127, np.uint8),
resize_side)
manager.detect(model_name, blank, prompts, device=device, conf=conf,
text_threshold=text_threshold, imgsz=imgsz)
loop_start = time.perf_counter()
while True:
ok, bgr = cap.read()
if not ok:
break
frame_idx += 1
if frame_idx % frame_skip != 0:
continue
if max_frames and processed >= max_frames:
break
frame = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
frame, _ = resize_long_side(frame, resize_side)
result = manager.detect(model_name, frame, prompts, device=device, conf=conf,
text_threshold=text_threshold, imgsz=imgsz)
total = info["total_frames"] or "?"
header = (f"Frame {frame_idx + 1}/{total} | {result['model_name']} | "
f"{result['num_detections']} det | {result['inference_time'] * 1000:.1f} ms")
annotated = draw_detections(frame, result, header=header)
if writer is None:
out_fps = info["fps"] / frame_skip
h, w = annotated.shape[:2]
writer, codec_used = create_video_writer(tmp_path, out_fps, (w, h), cfg["codecs"])
writer.write(cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR))
processed += 1
scores = result["scores"]
records.append({
"frame": frame_idx + 1,
"inference_ms": result["inference_time"] * 1000,
"num_detections": result["num_detections"],
"avg_confidence": float(np.mean(scores)) if scores else None,
})
if progress_callback:
progress_callback(frame_idx + 1, info["total_frames"], processed, annotated)
wall_time = time.perf_counter() - loop_start
finally:
cap.release()
if writer is not None:
writer.release()
if processed == 0:
tmp_path.unlink(missing_ok=True)
raise VideoError("No frames were processed - the video may be empty or unreadable.")
# Browser-playable H.264 when ffmpeg exists; otherwise keep the OpenCV file as written.
browser_playable = codec_used == "avc1"
if codec_used != "avc1" and reencode_h264(tmp_path, output_path):
tmp_path.unlink(missing_ok=True)
browser_playable = True
else:
shutil.move(str(tmp_path), str(output_path))
inference_total = sum(r["inference_ms"] for r in records) / 1000.0
stats = {
"model_name": model_name,
"output_path": str(output_path),
"codec": codec_used,
"browser_playable": browser_playable,
"input_fps": info["fps"],
"input_total_frames": info["total_frames"],
"input_duration_s": info["duration_s"],
"input_resolution": f"{info['width']}x{info['height']}",
"processed_frames": processed,
"frame_skip": frame_skip,
"frame_skip_enabled": frame_skip > 1,
"resize_long_side": resize_side or None,
"avg_inference_ms": 1000.0 * inference_total / processed,
"inference_fps": processed / inference_total if inference_total > 0 else float("nan"),
"end_to_end_fps": processed / wall_time if wall_time > 0 else float("nan"),
"total_processing_time_s": wall_time,
"total_detections": int(sum(r["num_detections"] for r in records)),
"per_frame": records,
"note": (f"Frame skipping enabled: every {frame_skip}th frame was processed and written; "
f"output plays at {info['fps'] / frame_skip:.2f} FPS." if frame_skip > 1
else "All frames were processed."),
}
logger.info("Video done: %d frames, inference %.1f FPS, end-to-end %.1f FPS",
processed, stats["inference_fps"], stats["end_to_end_fps"])
return stats
def main(argv: list[str] | None = None) -> int:
cfg = load_config()
parser = argparse.ArgumentParser(description="Open-vocabulary detection on a video.")
parser.add_argument("--video", required=True)
parser.add_argument("--model", default="YOLO-World")
parser.add_argument("--prompts", required=True, help="Comma-separated categories")
parser.add_argument("--device", default=cfg["device"]["default"])
parser.add_argument("--conf", type=float, default=None)
parser.add_argument("--text-threshold", type=float, default=None)
parser.add_argument("--frame-skip", type=int, default=None)
parser.add_argument("--resize-side", type=int, default=None)
parser.add_argument("--max-frames", type=int, default=None)
args = parser.parse_args(argv)
from models.model_manager import ModelManager, normalize_model_name
ensure_project_dirs()
out = resolve_path(cfg["paths"]["videos_out"]) / f"{Path(args.video).stem}_{int(time.time())}_annotated.mp4"
stats = process_video(ModelManager(), normalize_model_name(args.model), args.video, out,
parse_prompts(args.prompts), args.device, args.conf, args.text_threshold,
args.frame_skip, args.resize_side, max_frames=args.max_frames)
stats.pop("per_frame")
print(json.dumps(stats, indent=2, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())
+78
View File
@@ -0,0 +1,78 @@
"""Drawing detections and turning results into tables."""
from __future__ import annotations
import colorsys
import hashlib
import time
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
from utils.config_loader import load_config, resolve_path
def color_for_label(label: str) -> tuple[int, int, int]:
"""Stable RGB colour per category (same label -> same colour across runs)."""
digest = hashlib.md5(label.lower().encode("utf-8")).digest()
r, g, b = colorsys.hsv_to_rgb(digest[0] / 255.0, 0.75, 0.95)
return int(r * 255), int(g * 255), int(b * 255)
def draw_detections(image_rgb: np.ndarray, result: dict, header: str | None = None,
show_summary: bool = True) -> np.ndarray:
"""Return a copy of the image with boxes, 'label NN%' tags and a summary bar."""
canvas = image_rgb.copy()
h, w = canvas.shape[:2]
thickness = max(2, int(round(max(h, w) / 500)))
font_scale = max(0.5, min(h, w) / 900)
font = cv2.FONT_HERSHEY_SIMPLEX
text_thickness = max(1, thickness - 1)
for box, label, score in zip(result["boxes"], result["labels"], result["scores"]):
x1, y1, x2, y2 = (int(round(v)) for v in box)
color = color_for_label(label)
cv2.rectangle(canvas, (x1, y1), (x2, y2), color, thickness)
tag = f"{label} {score * 100:.0f}%"
(tw, th), baseline = cv2.getTextSize(tag, font, font_scale, text_thickness)
top = y1 - th - baseline - 4
if top < 0:
top = y1
cv2.rectangle(canvas, (x1, top), (x1 + tw + 6, top + th + baseline + 4), color, -1)
cv2.putText(canvas, tag, (x1 + 3, top + th + 1), font, font_scale, (0, 0, 0), text_thickness, cv2.LINE_AA)
if show_summary or header:
text = header or (f"{result['model_name']} | {result['num_detections']} detections | "
f"{result['inference_time'] * 1000:.1f} ms")
(tw, th), baseline = cv2.getTextSize(text, font, font_scale, text_thickness)
cv2.rectangle(canvas, (0, 0), (tw + 12, th + baseline + 10), (20, 24, 31), -1)
cv2.putText(canvas, text, (6, th + 5), font, font_scale, (255, 255, 255), text_thickness, cv2.LINE_AA)
return canvas
def result_to_dataframe(result: dict) -> pd.DataFrame:
"""Detections as a table (xyxy pixels in the original image)."""
columns = ["#", "label", "confidence_%", "x1", "y1", "x2", "y2", "width", "height"]
rows = []
for i, (box, label, score) in enumerate(zip(result["boxes"], result["labels"], result["scores"]), start=1):
x1, y1, x2, y2 = box
rows.append({"#": i, "label": label, "confidence_%": round(score * 100, 1),
"x1": round(x1, 1), "y1": round(y1, 1), "x2": round(x2, 1), "y2": round(y2, 1),
"width": round(x2 - x1, 1), "height": round(y2 - y1, 1)})
return pd.DataFrame(rows, columns=columns)
def save_annotated_image(image_rgb: np.ndarray, directory: str | Path | None = None,
stem: str = "detection") -> Path:
"""Save an RGB image as PNG under outputs/images (unicode-safe). Returns the file path."""
directory = Path(directory) if directory else resolve_path(load_config()["paths"]["images_out"])
directory.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y%m%d_%H%M%S") + f"_{int((time.time() % 1) * 1000):03d}"
safe_stem = "".join(c if c.isalnum() or c in "-_" else "_" for c in stem)[:60] or "detection"
path = directory / f"{safe_stem}_{stamp}.png"
ok, buf = cv2.imencode(".png", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR))
if not ok:
raise OSError("Could not encode the annotated image.")
path.write_bytes(buf.tobytes())
return path