Spaces:
Runtime error
Download KNOWLEDGE.md from npisb/pipecountapp-dev: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/main/KNOWLEDGE.md
- Command line
-
hf download hf://spaces/npisb/pipecountapp-dev/KNOWLEDGE.md
-
curl -L -o KNOWLEDGE.md https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/main/KNOWLEDGE.md
Pipe Counting Knowledge Base
v1.0 (2026) — The app is now an offline-first PWA with in-browser ONNX inference (
frontend/), diameter clustering, interactive correction, and client-side export. The Hugging Face Space serves static files only (main.py). Model export:scripts/export_onnx.py.
This document synthesizes key industry and research insights from CountThings (commercial leader) and Ivan Fenster's Medium article (award-winning academic/offline approach) with direct application notes for our local Pipe Counting PWA (pipecountapp) codebase.
1. Executive Summary & Core Concepts
Pipe counting is a critical computer vision task in industrial logistics, manufacturing, and metallurgy. The domain consists of two distinct paradigms:
- Commercial SaaS / Guided Multi-Class Platforms (e.g., CountThings): Focuses on high-touch interactive correction, multi-layered "pipes-in-pipes" classification, and rigorous audit trails.
- Offline-First High-Density Detection (e.g., Ivan Fenster / PipesCounting): Focuses on lightweight edge inference (TFLite/YOLO), synthetic dataset generation, and algorithmic post-processing to handle highly dense overlapping bundles.
Below is an in-depth breakdown of these two sources and how they can be used to advance our pipecountapp architecture.
2. CountThings: "Pipes in Pipes" Guide (ID: 466)
CountThings is the commercial standard for photographic counting. Their "Pipes in Pipes" counting template addresses the industry challenge of complex concentric/nested pipe bundles of varying diameters.
Key Workflows & Features
- Multi-Class Classification by Size: Enables detection and categorization of varying pipe diameters in a single photo (e.g., 75 mm, 110 mm, 180 mm, 250 mm).
- Expected Quantity Verification: Users can enter an "expected quantity" before running the count. The UI automatically highlights discrepancies between expected and detected values, acting as an automated QA/QC check.
- Interactive Correction UI:
- Tag Selection: Reclassify individual incorrectly detected sizes (e.g., if a 110 mm pipe is misidentified as a 180 mm pipe, select the target class and tap the pipe to correct it).
- Area Selection: Make bulk corrections across a custom drawn region of the image at once.
- Tag Correction (Add/Delete): Users can manually tap to add a missing tag or delete a spurious detection.
- Export Strategy: Saves a result photo for every individual pipe size counted, ensuring traceability and visual proof.
Relevance to Our Codebase
- Current State: Our
main.pyrelies on a single-class YOLOv5 model (countmodel.pt) that draws a sequential count indicator over each pipe end. - Future Enhancement:
- If our model expands to support multiple classes (e.g., different diameter ranges), we can implement tag filtering.
- We can expose the
/detect/jsoncoordinates to a frontend layer to allow manual "Tag Correction" (tap to delete, tap to add, drag to resize) and sync those modifications back to our count tracking.
3. Ivan Fenster (Medium): Offline AI Tool for Metallurgy
Ivan Fenster et al. (Letovo School) developed PipesCounting, an offline-first mobile app that placed 2nd in the International AI Junior Contest ("Metallurgy" category).
Technical Specifications
- Architecture: Fine-tuned YOLOv8, exported to TensorFlow Lite (LiteRT) for offline Android execution.
- APK Optimization: PyTorch was rejected as it inflated the APK size to 1.5 GB. Switching to TensorFlow Lite reduced the payload to 70 MB.
- Classes Detected: Four primary industrial profiles:
- Round pipes
- Square pipes
- Angle bars (L-shaped)
- Channel bars (U-shaped)
Dataset & Labeling
- Custom Dataset: Round and square datasets were acquired from open-source repositories, but angle and channel bars lacked datasets. The team manually labeled 12,000 pipes in CVAT.
- Roboflow Dataset Link: PipesCounting Dataset on Roboflow
- Augmentation:
- Flip: Doubles dataset size.
- Rotation (±15°): Helps with camera tilts on-site.
- Brightness/Exposure: Mimics variable lighting in production shops.
- Blur: Handles fast-moving or shaky mobile capture.
- Mosaic: Merges 4 frames to synthesize busy environments.
- Synthetic Data Generation:
- Production backgrounds were combined with cutoutends of real pipes using three stacking patterns: No pattern (randomly scattered), Simple pattern (rows, no nesting), and Complex pattern (nested).
- Finding: Surprisingly, synthetic data did not improve validation accuracy and occasionally degraded it. This was attributed to a lack of realism in the backgrounds and limited variation in pipe endpoints.
Algorithmic Highlights (Crucial for Dense Bundles)
- The "Large Bundle Problem": Standard YOLO networks experience a steep drop-off in detection quality on very dense clusters (e.g., >200 pipes). Some objects stop registering altogether.
- Overlapping Split Tiling Strategy:
- Split the image into 4 quadrant tiles with a small overlap.
- Run inference on each quadrant independently.
- Combine results and resolve duplicates at overlapping boundaries. Duplicate bboxes are merged by evaluating center-to-edge distance and keeping the larger bounding box.
- Outlier Filtering (Median Area Filter):
- In a bundle, physical pipes have uniform sizes. Spurious YOLO detections are often unusually small (random noise) or extremely large (merging multiple pipes).
- Algorithm: Compute the median area of all bounding boxes. Remove detections whose areas deviate significantly from this median.
4. Architectural Comparison & Optimization Plan
| Feature / Metric | pipecountapp (Our Codebase) |
PipesCounting (Medium Study) | Actionable Upgrade for Our Codebase |
|---|---|---|---|
| Model Version | YOLOv5 (countmodel.pt) |
YOLOv8 (yolov8x.pt to TFLite) |
Keep YOLOv5 for compatibility, but optimize inference thread count dynamically based on resource limits. |
| Inference Target | CPU (Optimized via OpenMP threads) | Edge CPU (TFLite / LiteRT) | We can deploy OpenVINO or ONNX Runtime to further accelerate server-side CPU inference. |
| Handling Large Bundles | Resizes original to MIN_IMAGE_HEIGHT=1500 and infers the full frame. |
Quadrant tiling with overlaps. | Feature Candidate: Introduce an optional tiling preprocessor in ImageProcessor for ultra-high-resolution or dense images. |
| Post-Processing Filtering | sort_detections_by_position (custom grid-based row sorting) |
Median Area Filter (Outlier removal) | Feature Candidate: Implement a filter_outliers method in ImageProcessor to drop boxes with area < 0.2x or > 3x the median box area. |
| Deployment Mode | Server-side API (FastAPI + Docker) | Client-side Offline (Kivy + Buildozer) | Keep API-first, but optimize image transfer overhead via configurable JPEG compression. |
5. Practical Code Implementations for Future Enhancement
A. Median Area Outlier Filter (Python / OpenCV)
To stabilize counts on noisy images, we can add this filter directly to our ImageProcessor class:
def filter_outliers(detections: List[Dict[str, Any]], lower_mult: float = 0.25, upper_mult: float = 4.0) -> List[Dict[str, Any]]:
"""
Filters out spurious bboxes that are significantly smaller or larger
than the median pipe size in the bundle.
"""
if not detections:
return []
# Calculate areas
areas = []
for d in detections:
w = d['xmax'] - d['xmin']
h = d['ymax'] - d['ymin']
areas.append(w * h)
median_area = np.median(areas)
filtered = []
for i, d in enumerate(detections):
area = areas[i]
# Keep only detections within the threshold scale of the median
if (median_area * lower_mult) <= area <= (median_area * upper_mult):
filtered.append(d)
return filtered
B. Quadrant Tiling Preprocessor (Python)
For high-density pictures where YOLO misses pipes due to size ratios, we can process overlapping quadrants:
def tile_inference(image: np.ndarray, model, overlap_ratio: float = 0.1) -> List[Dict[str, Any]]:
"""
Splits the image into 4 quadrants with overlap, infers each,
and applies custom NMS / Duplication resolution on the combined list.
"""
h, w = image.shape[:2]
mid_y, mid_x = h // 2, w // 2
dy = int(mid_y * overlap_ratio)
dx = int(mid_x * overlap_ratio)
# Define bounding coordinates of 4 overlapping quadrants
quadrants = [
# Top-Left
(0, mid_y + dy, 0, mid_x + dx),
# Top-Right
(0, mid_y + dy, mid_x - dx, w),
# Bottom-Left
(mid_y - dy, h, 0, mid_x + dx),
# Bottom-Right
(mid_y - dy, h, mid_x - dx, w)
]
all_detections = []
for ymin, ymax, xmin, xmax in quadrants:
crop = image[ymin:ymax, xmin:xmax]
results = model(crop)
dets = results.pandas().xyxy[0].to_dict('records')
# Translate coordinates back to full image coordinate space
for d in dets:
d['xmin'] += xmin
d['xmax'] += xmin
d['ymin'] += ymin
d['ymax'] += ymax
all_detections.append(d)
# Apply deduplication logic based on center proximity or standard NMS
return deduplicate_detections(all_detections)
6. Resources & Citation
- CountThings Pipes-in-Pipes Guide: https://countthings.com/en/guides/0003
- Ivan Fenster Medium Article: https://medium.com/@ivanfenster/developing-pipes-counting-how-to-build-an-offline-ai-tool-for-metalurgy-3b5d6df46007
- Roboflow Dataset: https://universe.roboflow.com/ignat/pipescounting_dataset-t7yey