Spaces:
Sleeping
Sleeping
Khunndev commited on
Commit ·
5cc7f8f
1
Parent(s): 85d22aa
Add Gradio pipe counting app
Browse files- .gitignore +1 -0
- README.md +41 -2
- app.py +173 -0
- huggingface.yaml +5 -0
- model/best.onnx +3 -0
- model/config.ini +17 -0
- pipe_counter/__init__.py +1 -0
- pipe_counter/inference.py +226 -0
- requirements.txt +5 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__pycache__/\n*.pyc\n
|
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
title: PIPECOUNTv2
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: yellow
|
| 6 |
sdk: gradio
|
|
@@ -10,4 +10,43 @@ pinned: false
|
|
| 10 |
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: PIPECOUNTv2
|
| 3 |
+
emoji: 🎯
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: yellow
|
| 6 |
sdk: gradio
|
|
|
|
| 10 |
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# PVC Pipe Counter
|
| 14 |
+
|
| 15 |
+
PVC pipe counting web application powered by a custom Ultralytics ONNX model. The interface mirrors the CountThings workflow with guided settings, annotated visual QA, and export-friendly results, ready for deployment on Hugging Face Spaces.
|
| 16 |
+
|
| 17 |
+
## Key Features
|
| 18 |
+
- 🧠 **ONNX-powered detection** – wraps `model/best.onnx` with ONNX Runtime for fast CPU inference.
|
| 19 |
+
- 🎯 **CountThings-inspired UX** – upload, tune thresholds, and view highlighted detections with running totals.
|
| 20 |
+
- 📊 **Structured output** – per-pipe coordinate table for downstream auditing or exporting.
|
| 21 |
+
- ☁️ **Space-ready** – Gradio front end with requirements and configuration for automatic builds.
|
| 22 |
+
|
| 23 |
+
## Project Structure
|
| 24 |
+
```
|
| 25 |
+
.
|
| 26 |
+
├── app.py # Gradio Blocks UI and event wiring
|
| 27 |
+
├── pipe_counter/ # Inference helpers
|
| 28 |
+
│ ├── __init__.py
|
| 29 |
+
│ └── inference.py # Letterbox preprocessing, ONNX Runtime session, post-processing
|
| 30 |
+
├── model/
|
| 31 |
+
│ └── best.onnx # Trained Ultralytics YOLO model (single PVC class)
|
| 32 |
+
├── requirements.txt # Runtime dependencies for Spaces / local use
|
| 33 |
+
├── huggingface.yaml # Hugging Face Space metadata (Gradio SDK)
|
| 34 |
+
└── README.md
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Local Development
|
| 38 |
+
1. Create and activate a Python 3.10 environment.
|
| 39 |
+
2. Install dependencies:
|
| 40 |
+
```bash
|
| 41 |
+
pip install -r requirements.txt
|
| 42 |
+
```
|
| 43 |
+
3. Run the app locally:
|
| 44 |
+
```bash
|
| 45 |
+
python app.py
|
| 46 |
+
```
|
| 47 |
+
Gradio launches a local server and prints the URL for testing.
|
| 48 |
+
|
| 49 |
+
## Deployment Notes
|
| 50 |
+
- Upload or push all repository contents (including `model/best.onnx`) to the Space; `.gitattributes` is already configured for Git LFS so large models sync correctly.
|
| 51 |
+
- The ONNX metadata indicates Ultralytics YOLO v8 (`stride=32`, `imgsz=640`). Adjust the confidence/IoU sliders in the UI to suit different camera angles or lighting conditions.
|
| 52 |
+
- For markedly different bundle layouts, fine-tune the model and replace `model/best.onnx` with the new weights.
|
app.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
from pipe_counter import Detection, PipeCounter
|
| 8 |
+
|
| 9 |
+
_MODEL: PipeCounter | None = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_model() -> PipeCounter:
|
| 13 |
+
global _MODEL
|
| 14 |
+
if _MODEL is None:
|
| 15 |
+
_MODEL = PipeCounter()
|
| 16 |
+
return _MODEL
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _format_detections(detections: list[Detection]) -> list[list[int | float | str]]:
|
| 20 |
+
rows: list[list[int | float | str]] = []
|
| 21 |
+
for idx, det in enumerate(detections, start=1):
|
| 22 |
+
x1, y1, x2, y2 = det.box
|
| 23 |
+
rows.append(
|
| 24 |
+
[
|
| 25 |
+
idx,
|
| 26 |
+
det.label,
|
| 27 |
+
round(det.confidence, 3),
|
| 28 |
+
x1,
|
| 29 |
+
y1,
|
| 30 |
+
x2,
|
| 31 |
+
y2,
|
| 32 |
+
]
|
| 33 |
+
)
|
| 34 |
+
return rows
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def count_pipes(
|
| 38 |
+
image: np.ndarray | None,
|
| 39 |
+
confidence: float,
|
| 40 |
+
iou: float,
|
| 41 |
+
) -> tuple[Image.Image | None, str, int, list[list[int | float | str]]]:
|
| 42 |
+
if image is None:
|
| 43 |
+
return None, "Upload an image to analyze PVC bundles.", 0, []
|
| 44 |
+
|
| 45 |
+
model = get_model()
|
| 46 |
+
detections, annotated = model.predict(image, confidence=confidence, iou=iou)
|
| 47 |
+
count = len(detections)
|
| 48 |
+
message = (
|
| 49 |
+
f"Detected **{count}** pipes at confidence ≥ {confidence:.2f}."
|
| 50 |
+
if count
|
| 51 |
+
else "No pipes detected. Try lowering the confidence threshold or uploading a sharper image."
|
| 52 |
+
)
|
| 53 |
+
table = _format_detections(detections)
|
| 54 |
+
return annotated, message, count, table
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def reset_view() -> tuple[None, str, int, object]:
|
| 58 |
+
return None, "Upload an image to begin.", 0, gr.update(value=[])
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
DESCRIPTION = """
|
| 62 |
+
<div style="display:flex;gap:1.5rem;flex-wrap:wrap;align-items:center;justify-content:space-between;">
|
| 63 |
+
<div>
|
| 64 |
+
<h1 style="margin-bottom:0.25rem;">PVC Pipe Counter</h1>
|
| 65 |
+
<p style="margin:0;color:#4d4d4d;font-size:0.95rem;max-width:38rem;">
|
| 66 |
+
Automated counting for pipe bundles inspired by the CountThings workflow. Upload a rack photo,
|
| 67 |
+
adjust thresholds, and review bounding boxes with per-pipe confidence to accelerate QA and inventory tasks.
|
| 68 |
+
</p>
|
| 69 |
+
</div>
|
| 70 |
+
<div style="min-width:220px;background:#f3f7ff;border-radius:12px;padding:1rem 1.25rem;border:1px solid #d5e1ff;">
|
| 71 |
+
<h3 style="margin-top:0;margin-bottom:0.5rem;font-size:1rem;">Workflow</h3>
|
| 72 |
+
<ol style="margin:0;padding-left:1.1rem;font-size:0.85rem;color:#445;">
|
| 73 |
+
<li>Capture or upload a pipe bundle image.</li>
|
| 74 |
+
<li>Fine-tune the detection thresholds (confidence / IoU).</li>
|
| 75 |
+
<li>Download the annotated result or export the count sheet.</li>
|
| 76 |
+
</ol>
|
| 77 |
+
</div>
|
| 78 |
+
</div>
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
FEATURE_CALLOUT = """
|
| 82 |
+
<div style="display:flex;gap:1rem;flex-wrap:wrap;">
|
| 83 |
+
<div style="flex:1 1 220px;background:#fff7ed;border:1px solid #ffd8a8;border-radius:10px;padding:0.85rem;">
|
| 84 |
+
<h4 style="margin:0 0 0.35rem 0;">Visual QA</h4>
|
| 85 |
+
<p style="margin:0;color:#4c3d2b;font-size:0.85rem;">Overlay detections with labeled bounding boxes to cross-check tricky bundles.</p>
|
| 86 |
+
</div>
|
| 87 |
+
<div style="flex:1 1 220px;background:#ecfdf3;border:1px solid #bbf7d0;border-radius:10px;padding:0.85rem;">
|
| 88 |
+
<h4 style="margin:0 0 0.35rem 0;">Adjustable Sensitivity</h4>
|
| 89 |
+
<p style="margin:0;color:#1f492f;font-size:0.85rem;">Control confidence and overlap thresholds to match on-site lighting and camera angles.</p>
|
| 90 |
+
</div>
|
| 91 |
+
<div style="flex:1 1 220px;background:#eef2ff;border:1px solid #c7d2fe;border-radius:10px;padding:0.85rem;">
|
| 92 |
+
<h4 style="margin:0 0 0.35rem 0;">Structured Output</h4>
|
| 93 |
+
<p style="margin:0;color:#1f2563;font-size:0.85rem;">Export-ready table with per-pipe coordinates for downstream reconciliation.</p>
|
| 94 |
+
</div>
|
| 95 |
+
</div>
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
CSS = """
|
| 99 |
+
:root {
|
| 100 |
+
--radius-lg: 14px;
|
| 101 |
+
}
|
| 102 |
+
.gradio-container {background: #f5f7fb;}
|
| 103 |
+
.block {border-radius: var(--radius-lg)!important;}
|
| 104 |
+
button.primary {background: linear-gradient(135deg,#4361ee,#5e60ce)!important;}
|
| 105 |
+
footer {display:none!important;}
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def build_demo() -> gr.Blocks:
|
| 110 |
+
with gr.Blocks(css=CSS, theme=gr.themes.Soft(primary_hue="indigo")) as demo:
|
| 111 |
+
gr.HTML(DESCRIPTION)
|
| 112 |
+
gr.Markdown(FEATURE_CALLOUT)
|
| 113 |
+
|
| 114 |
+
with gr.Row(equal_height=True):
|
| 115 |
+
with gr.Column(scale=5, min_width=360):
|
| 116 |
+
image_input = gr.Image(
|
| 117 |
+
label="Upload Pipe Bundle",
|
| 118 |
+
type="numpy",
|
| 119 |
+
image_mode="RGB",
|
| 120 |
+
height=360,
|
| 121 |
+
)
|
| 122 |
+
with gr.Accordion("Detection Settings", open=False):
|
| 123 |
+
confidence_slider = gr.Slider(
|
| 124 |
+
minimum=0.05,
|
| 125 |
+
maximum=0.95,
|
| 126 |
+
value=0.45,
|
| 127 |
+
step=0.05,
|
| 128 |
+
label="Confidence Threshold",
|
| 129 |
+
)
|
| 130 |
+
iou_slider = gr.Slider(
|
| 131 |
+
minimum=0.1,
|
| 132 |
+
maximum=0.9,
|
| 133 |
+
value=0.45,
|
| 134 |
+
step=0.05,
|
| 135 |
+
label="IoU Threshold",
|
| 136 |
+
)
|
| 137 |
+
run_button = gr.Button("Count Pipes", variant="primary")
|
| 138 |
+
reset_button = gr.Button("Clear", variant="secondary")
|
| 139 |
+
status = gr.Markdown("Upload an image to begin.")
|
| 140 |
+
|
| 141 |
+
with gr.Column(scale=7, min_width=420):
|
| 142 |
+
output_image = gr.Image(label="Detections", show_label=True, height=420)
|
| 143 |
+
with gr.Row():
|
| 144 |
+
count_badge = gr.Number(label="Total Pipes", value=0, precision=0)
|
| 145 |
+
gr.Markdown("Use the table for inspection and exporting.")
|
| 146 |
+
table = gr.Dataframe(
|
| 147 |
+
headers=["#", "Label", "Confidence", "X1", "Y1", "X2", "Y2"],
|
| 148 |
+
datatype=["number", "str", "number", "number", "number", "number", "number"],
|
| 149 |
+
interactive=False,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
run_button.click(
|
| 153 |
+
count_pipes,
|
| 154 |
+
inputs=[image_input, confidence_slider, iou_slider],
|
| 155 |
+
outputs=[output_image, status, count_badge, table],
|
| 156 |
+
)
|
| 157 |
+
image_input.upload(
|
| 158 |
+
count_pipes,
|
| 159 |
+
inputs=[image_input, confidence_slider, iou_slider],
|
| 160 |
+
outputs=[output_image, status, count_badge, table],
|
| 161 |
+
)
|
| 162 |
+
reset_button.click(
|
| 163 |
+
reset_view,
|
| 164 |
+
outputs=[output_image, status, count_badge, table],
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
return demo
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
demo = build_demo()
|
| 171 |
+
|
| 172 |
+
if __name__ == "__main__":
|
| 173 |
+
demo.launch()
|
huggingface.yaml
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sdk: gradio
|
| 2 |
+
sdk_version: 5.47.2
|
| 3 |
+
python_version: 3.10
|
| 4 |
+
app_file: app.py
|
| 5 |
+
title: PVC Pipe Counter
|
model/best.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b37f26ffba86408663df14dbd295abc998c85eba0b88236936b945aacd0a96e9
|
| 3 |
+
size 12364505
|
model/config.ini
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on your trained model performance: mAP50: 84.15% at conf=0.25
|
| 2 |
+
OPTIMAL_INFERENCE_PARAMS = {
|
| 3 |
+
# Core Detection Parameters
|
| 4 |
+
'confidence_threshold': 0.25, # Sweet spot for your model
|
| 5 |
+
'iou_threshold': 0.45, # Standard NMS threshold
|
| 6 |
+
'max_detections': 2000, # Max objects per image
|
| 7 |
+
|
| 8 |
+
# Image Processing
|
| 9 |
+
'input_size': 640, # Match training size
|
| 10 |
+
'maintain_aspect_ratio': True, # Better accuracy
|
| 11 |
+
'padding_color': 114, # YOLOv8 standard
|
| 12 |
+
|
| 13 |
+
# Performance Optimization
|
| 14 |
+
'batch_size': 1, # Real-time processing
|
| 15 |
+
'use_fp16': False, # Better accuracy for production
|
| 16 |
+
'dynamic_batching': False, # Consistent latency
|
| 17 |
+
}
|
pipe_counter/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .inference import Detection, PipeCounter
|
pipe_counter/inference.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List, Optional, Sequence, Tuple, Union
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import onnxruntime as ort
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
ArrayLike = Union[str, Path, Image.Image, np.ndarray]
|
| 13 |
+
_PALETTE = [
|
| 14 |
+
(46, 204, 113),
|
| 15 |
+
(52, 152, 219),
|
| 16 |
+
(231, 76, 60),
|
| 17 |
+
(155, 89, 182),
|
| 18 |
+
(241, 196, 15),
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class Detection:
|
| 24 |
+
box: Tuple[int, int, int, int]
|
| 25 |
+
confidence: float
|
| 26 |
+
label: str
|
| 27 |
+
class_id: int
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _sigmoid(x: np.ndarray) -> np.ndarray:
|
| 31 |
+
return 1.0 / (1.0 + np.exp(-x))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
|
| 35 |
+
xyxy = boxes.copy()
|
| 36 |
+
xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
|
| 37 |
+
xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
|
| 38 |
+
xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
|
| 39 |
+
xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
|
| 40 |
+
return xyxy
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _letterbox(
|
| 44 |
+
image: np.ndarray,
|
| 45 |
+
new_shape: Tuple[int, int] = (640, 640),
|
| 46 |
+
color: Tuple[int, int, int] = (114, 114, 114),
|
| 47 |
+
) -> Tuple[np.ndarray, Tuple[float, float], Tuple[float, float]]:
|
| 48 |
+
shape = image.shape[:2]
|
| 49 |
+
if isinstance(new_shape, int):
|
| 50 |
+
new_shape = (new_shape, new_shape)
|
| 51 |
+
|
| 52 |
+
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
| 53 |
+
r = min(r, 1.0)
|
| 54 |
+
ratio = (r, r)
|
| 55 |
+
|
| 56 |
+
new_unpad = (int(round(shape[1] * r)), int(round(shape[0] * r)))
|
| 57 |
+
dw = new_shape[1] - new_unpad[0]
|
| 58 |
+
dh = new_shape[0] - new_unpad[1]
|
| 59 |
+
dw /= 2
|
| 60 |
+
dh /= 2
|
| 61 |
+
|
| 62 |
+
if new_unpad != (shape[1], shape[0]):
|
| 63 |
+
image = cv2.resize(image, new_unpad, interpolation=cv2.INTER_LINEAR)
|
| 64 |
+
|
| 65 |
+
top = int(round(dh - 0.1))
|
| 66 |
+
bottom = int(round(dh + 0.1))
|
| 67 |
+
left = int(round(dw - 0.1))
|
| 68 |
+
right = int(round(dw + 0.1))
|
| 69 |
+
|
| 70 |
+
image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
|
| 71 |
+
return image, ratio, (dw, dh)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _iou(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:
|
| 75 |
+
if not len(boxes):
|
| 76 |
+
return np.empty((0,), dtype=np.float32)
|
| 77 |
+
x1 = np.maximum(box[0], boxes[:, 0])
|
| 78 |
+
y1 = np.maximum(box[1], boxes[:, 1])
|
| 79 |
+
x2 = np.minimum(box[2], boxes[:, 2])
|
| 80 |
+
y2 = np.minimum(box[3], boxes[:, 3])
|
| 81 |
+
|
| 82 |
+
inter = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
|
| 83 |
+
box_area = (box[2] - box[0]) * (box[3] - box[1])
|
| 84 |
+
boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
|
| 85 |
+
union = box_area + boxes_area - inter + 1e-9
|
| 86 |
+
return inter / union
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _nms(boxes: np.ndarray, scores: np.ndarray, iou_thres: float, max_det: int) -> List[int]:
|
| 90 |
+
if not len(boxes):
|
| 91 |
+
return []
|
| 92 |
+
idxs = scores.argsort()[::-1]
|
| 93 |
+
keep: List[int] = []
|
| 94 |
+
while idxs.size > 0 and len(keep) < max_det:
|
| 95 |
+
i = idxs[0]
|
| 96 |
+
keep.append(int(i))
|
| 97 |
+
if idxs.size == 1:
|
| 98 |
+
break
|
| 99 |
+
ious = _iou(boxes[i], boxes[idxs[1:]])
|
| 100 |
+
idxs = idxs[1:][ious < iou_thres]
|
| 101 |
+
return keep
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class PipeCounter:
|
| 105 |
+
def __init__(
|
| 106 |
+
self,
|
| 107 |
+
model_path: Union[str, Path] = Path("model/best.onnx"),
|
| 108 |
+
providers: Optional[Sequence[str]] = None,
|
| 109 |
+
confidence_threshold: float = 0.45,
|
| 110 |
+
iou_threshold: float = 0.45,
|
| 111 |
+
image_size: int = 640,
|
| 112 |
+
max_detections: int = 300,
|
| 113 |
+
) -> None:
|
| 114 |
+
self.model_path = Path(model_path)
|
| 115 |
+
if not self.model_path.exists():
|
| 116 |
+
raise FileNotFoundError(f"Model file not found: {self.model_path}")
|
| 117 |
+
self.confidence_threshold = confidence_threshold
|
| 118 |
+
self.iou_threshold = iou_threshold
|
| 119 |
+
self.image_size = image_size
|
| 120 |
+
self.max_detections = max_detections
|
| 121 |
+
self.session = ort.InferenceSession(str(self.model_path), providers=providers or ["CPUExecutionProvider"])
|
| 122 |
+
self.input_name = self.session.get_inputs()[0].name
|
| 123 |
+
meta = self.session.get_modelmeta().custom_metadata_map
|
| 124 |
+
self.labels = self._parse_labels(meta.get("names", "{0: 'pipe'}"))
|
| 125 |
+
self.num_classes = max(len(self.labels), 1)
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _parse_labels(raw: str) -> List[str]:
|
| 129 |
+
try:
|
| 130 |
+
mapping = eval(raw)
|
| 131 |
+
return [mapping.get(i, f"class_{i}") for i in sorted(mapping)]
|
| 132 |
+
except Exception:
|
| 133 |
+
return ["pipe"]
|
| 134 |
+
|
| 135 |
+
def _to_numpy(self, data: ArrayLike) -> np.ndarray:
|
| 136 |
+
if isinstance(data, np.ndarray):
|
| 137 |
+
if data.ndim == 2:
|
| 138 |
+
data = np.stack([data] * 3, axis=-1)
|
| 139 |
+
if data.shape[2] == 4:
|
| 140 |
+
data = data[:, :, :3]
|
| 141 |
+
return data
|
| 142 |
+
if isinstance(data, (str, Path)):
|
| 143 |
+
data = Image.open(data)
|
| 144 |
+
if isinstance(data, Image.Image):
|
| 145 |
+
data = data.convert("RGB")
|
| 146 |
+
return np.array(data)
|
| 147 |
+
raise TypeError("Unsupported input type for image data")
|
| 148 |
+
|
| 149 |
+
def _prepare(self, image: np.ndarray) -> Tuple[np.ndarray, Tuple[float, float], Tuple[float, float]]:
|
| 150 |
+
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
| 151 |
+
processed, ratio, pad = _letterbox(image_bgr, (self.image_size, self.image_size))
|
| 152 |
+
processed = processed.astype(np.float32) / 255.0
|
| 153 |
+
processed = np.transpose(processed, (2, 0, 1))
|
| 154 |
+
processed = np.expand_dims(processed, axis=0)
|
| 155 |
+
return processed, ratio, pad
|
| 156 |
+
|
| 157 |
+
def predict(
|
| 158 |
+
self,
|
| 159 |
+
data: ArrayLike,
|
| 160 |
+
confidence: Optional[float] = None,
|
| 161 |
+
iou: Optional[float] = None,
|
| 162 |
+
) -> Tuple[List[Detection], Image.Image]:
|
| 163 |
+
conf_thres = confidence if confidence is not None else self.confidence_threshold
|
| 164 |
+
iou_thres = iou if iou is not None else self.iou_threshold
|
| 165 |
+
|
| 166 |
+
image = self._to_numpy(data)
|
| 167 |
+
original = image.copy()
|
| 168 |
+
blob, ratio, pad = self._prepare(image)
|
| 169 |
+
outputs = self.session.run(None, {self.input_name: blob})[0]
|
| 170 |
+
preds = outputs[0]
|
| 171 |
+
preds = preds.reshape(preds.shape[0], -1)
|
| 172 |
+
|
| 173 |
+
boxes = preds[:4, :].T
|
| 174 |
+
class_scores = preds[4:, :]
|
| 175 |
+
if class_scores.size == 0:
|
| 176 |
+
class_scores = np.zeros((1, boxes.shape[0]), dtype=np.float32)
|
| 177 |
+
class_scores = _sigmoid(class_scores).T
|
| 178 |
+
|
| 179 |
+
boxes = _xywh_to_xyxy(boxes)
|
| 180 |
+
boxes[:, [0, 2]] -= pad[0]
|
| 181 |
+
boxes[:, [1, 3]] -= pad[1]
|
| 182 |
+
boxes[:, [0, 2]] /= ratio[0]
|
| 183 |
+
boxes[:, [1, 3]] /= ratio[1]
|
| 184 |
+
boxes[:, 0] = np.clip(boxes[:, 0], 0, original.shape[1])
|
| 185 |
+
boxes[:, 1] = np.clip(boxes[:, 1], 0, original.shape[0])
|
| 186 |
+
boxes[:, 2] = np.clip(boxes[:, 2], 0, original.shape[1])
|
| 187 |
+
boxes[:, 3] = np.clip(boxes[:, 3], 0, original.shape[0])
|
| 188 |
+
|
| 189 |
+
class_ids = class_scores.argmax(axis=1)
|
| 190 |
+
scores = class_scores.max(axis=1)
|
| 191 |
+
|
| 192 |
+
mask = scores >= conf_thres
|
| 193 |
+
boxes = boxes[mask]
|
| 194 |
+
scores = scores[mask]
|
| 195 |
+
class_ids = class_ids[mask]
|
| 196 |
+
|
| 197 |
+
if not len(scores):
|
| 198 |
+
annotated = self._draw(original, [])
|
| 199 |
+
return [], annotated
|
| 200 |
+
|
| 201 |
+
keep = _nms(boxes, scores, iou_thres, self.max_detections)
|
| 202 |
+
detections = [
|
| 203 |
+
Detection(
|
| 204 |
+
box=(int(boxes[i][0]), int(boxes[i][1]), int(boxes[i][2]), int(boxes[i][3])),
|
| 205 |
+
confidence=float(scores[i]),
|
| 206 |
+
label=self.labels[class_ids[i]] if class_ids[i] < len(self.labels) else f"class_{class_ids[i]}",
|
| 207 |
+
class_id=int(class_ids[i]),
|
| 208 |
+
)
|
| 209 |
+
for i in keep
|
| 210 |
+
]
|
| 211 |
+
annotated = self._draw(original, detections)
|
| 212 |
+
return detections, annotated
|
| 213 |
+
|
| 214 |
+
def _draw(self, image: np.ndarray, detections: Sequence[Detection]) -> Image.Image:
|
| 215 |
+
canvas = image.copy()
|
| 216 |
+
canvas = cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR)
|
| 217 |
+
for det in detections:
|
| 218 |
+
x1, y1, x2, y2 = det.box
|
| 219 |
+
color = _PALETTE[det.class_id % len(_PALETTE)]
|
| 220 |
+
cv2.rectangle(canvas, (x1, y1), (x2, y2), color, 2)
|
| 221 |
+
label = f"{det.label} {det.confidence:.2f}"
|
| 222 |
+
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
|
| 223 |
+
cv2.rectangle(canvas, (x1, max(0, y1 - th - 6)), (x1 + tw + 2, y1), color, -1)
|
| 224 |
+
cv2.putText(canvas, label, (x1 + 1, max(12, y1 - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
|
| 225 |
+
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
|
| 226 |
+
return Image.fromarray(canvas)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.47.2
|
| 2 |
+
onnxruntime==1.23.0
|
| 3 |
+
opencv-python-headless==4.12.0.88
|
| 4 |
+
Pillow==11.1.0
|
| 5 |
+
numpy==2.2.6
|