CoolFace
Apppublic

sonson0910/engineering-drawing-detection

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
App README

Engineering Drawing Object Detection and OCR System

Technical Assessment โ€” Sotatek Computer Vision / AI Engineer

An end-to-end pipeline for detecting and extracting structured information from engineering drawings using a commercially-licensed detection model, advanced post-processing, and a full OCR stack.

๐Ÿ”— Live Demo: huggingface.co/spaces/sonson0910/engineering-drawing-detection ๐Ÿ“ฆ Model Weights: Download best_model.pth (Google Drive)


Table of Contents


Overview

The system detects three classes of objects in engineering drawings:

ClassColourDescription
PartDrawing๐ŸŸข GreenTechnical drawing / schematic regions
Note๐ŸŸ  OrangeText annotations, callouts, specification text
Table๐Ÿ”ต BlueBOM tables, title blocks, data tables

Architecture

Input Image
  โ†’ [TTA] Multi-scale + flip augmentation (6 views)
  โ†’ Faster R-CNN ResNet-50 FPN v2  (inference on each view)
  โ†’ Weighted Boxes Fusion (WBF)    (merge all view predictions)
  โ†’ Per-class NMS + size filtering
  โ†’ Content-aware box tightening
  โ†’ [Overlap Resolution] Priority-based arbitration
      Table > Note > PartDrawing
      Each overlap pixel classified by visual content:
        grid lines โ†’ Table | dense text โ†’ Note | sparse geometry โ†’ PartDrawing
  โ†’ Crop detected regions
      โ”œโ”€โ”€ PartDrawing โ†’ save crop image
      โ”œโ”€โ”€ Note        โ†’ PaddleOCR text extraction
      โ””โ”€โ”€ Table       โ†’ PaddleOCR PP-Structure (HTML table output)
  โ†’ JSON output + visualization

Framework Choice

CriterionChoiceRationale
Detection modelFaster R-CNN ResNet-50 FPN v2BSD-3 licensed (torchvision), commercially compatible. Two-stage detector excels at medium/large objects with complex aspect ratios
OCRPaddleOCRApache 2.0 license, built-in angle correction, high accuracy on dense technical text
Table structurePPStructurePreserves row/column alignment; outputs structured HTML
โš ๏ธ YOLO was explicitly excluded due to AGPL-3.0 licensing restrictions on commercial use.

Key Techniques

1. Test-Time Augmentation (TTA) with WBF

At inference time, the model runs on 6 augmented views of each input image:

  • โ€”3 scales: 0.75ร—, 1.0ร—, 1.25ร—
  • โ€”Each scale: original + horizontal flip

All 6 sets of predictions are fused via Weighted Boxes Fusion (WBF) โ€” a state-of-the-art ensemble method that averages box coordinates weighted by confidence scores, rather than simply suppressing low-confidence duplicates like standard NMS.

This delivers ~5โ€“10% higher recall with no retraining, at ~6ร— inference cost.

2. Overlap Resolution

Per the assessment requirement:

"There may be cases where bounding boxes overlap. You will need to properly separate these overlapping regions and determine which specific bounding box each area belongs to."

The overlap_resolver.py module implements a 3-tier arbitration system:

  1. 1.Class priority rule: Table > Note > PartDrawing Engineering drawings are structured such that when two objects overlap:
  2. 2.A Table almost always takes precedence (it has defined borders)
  3. 3.A Note annotation takes precedence over a general drawing area
  4. 4.Confidence score tiebreaker: higher confidence wins when priority is equal
  5. 5.Visual content analysis: each overlap pixel-patch is analyzed:
  6. 6.Grid/line structure โ†’ Table
  7. 7.Dense horizontal text rows โ†’ Note
  8. 8.Sparse geometric content โ†’ PartDrawing

The resolution runs iteratively until zero overlapping pairs remain. Every resolved overlap is logged in the JSON output under overlap_resolution.details[] for full transparency.

3. Training Enhancements

TechniqueImplementation
OptimizerAdamW (better generalization on small datasets vs SGD)
LR SchedulerCosineAnnealingWarmRestarts (Tโ‚€=20, Tmult=2) โ€” periodic restarts escape local minima
Data AugmentationCLAHE, Perspective, Gaussian/Motion/Median blur, CoarseDropout, ImageCompression, Affine
Copy-PasteNote regions pasted into empty areas of other images โ†’ ~5ร— effective Note annotations
OversamplingWeightedRandomSampler: Note images 4ร— weight, Table images 2ร— weight
Anchor tuningFPN multi-scale anchors handle Note (small), Table (medium) and PartDrawing (large)

4. Post-Processing Pipeline

Raw model predictions
  โ†’ Min threshold filter (class-specific)
  โ†’ Per-class NMS (standard for PartDrawing/Note; prefer-larger variant for Table)
  โ†’ Size filter (min_w ร— min_h ร— area per class)
  โ†’ Content-aware box tightening (morphological trimming of white margins)
  โ†’ Iterative overlap resolution (see above)

Setup and Installation

Prerequisites

  • โ€”Python 3.10+
  • โ€”PyTorch 2.0+ (CUDA-capable GPU recommended, 8GB+ VRAM)

Installation

bash
git clone https://github.com/<your-username>/cv-assessment.git
cd cv-assessment

python -m venv venv
# Windows:
venv\Scripts\activate
# Linux/macOS:
source venv/bin/activate

pip install -r requirements.txt

Dataset

COCO format, 58 images, 412 annotations across 3 classes:

datasets/
โ””โ”€โ”€ BOM-Folder- BOM-Dataset.coco/
    โ””โ”€โ”€ train/
        โ”œโ”€โ”€ _annotations.coco.json
        โ””โ”€โ”€ *.png

Training

bash
python src/detection/train.py

Key configuration (config/train_config.yaml):

ParameterValue
BackboneResNet-50 FPN v2
Pre-trained weightsCOCO
OptimizerAdamW
Learning rate1e-4
SchedulerCosineAnnealingWarmRestarts
Epochs80
Batch size2
Copy-Paste augmentationโœ…
Note oversampling4ร—

Achieved Results

MetricValue
mAP@500.94
PartDrawing AP~0.98
Note AP~0.87
Table AP~0.97

Inference

Single image

bash
python src/detection/inference.py \
    --model models/best_map_model_backup.pth \
    --input path/to/image.jpg \
    --output outputs/

Batch directory

bash
python src/pipeline/pipeline.py \
    --model models/best_map_model_backup.pth \
    --input path/to/images/ \
    --output outputs/

Output structure

outputs/
โ”œโ”€โ”€ crops/
โ”‚   โ”œโ”€โ”€ PartDrawing/
โ”‚   โ”œโ”€โ”€ Note/
โ”‚   โ””โ”€โ”€ Table/
โ”œโ”€โ”€ visualizations/
โ””โ”€โ”€ json/

JSON schema

json
{
  "image": "drawing_001.jpg",
  "objects": [
    {
      "id": 1,
      "class": "Table",
      "confidence": 0.97,
      "bbox": { "x1": 120, "y1": 340, "x2": 680, "y2": 520 },
      "ocr_content": {
        "type": "table",
        "rows": [["Header1", "Header2"], ["Data1", "Data2"]],
        "html": "<table>...</table>",
        "raw_text": "Header1 | Header2\nData1 | Data2"
      }
    }
  ],
  "overlap_resolution": {
    "total_overlaps_detected": 1,
    "details": [
      {
        "box_a": { "class": "PartDrawing", "score": 0.91 },
        "box_b": { "class": "Table", "score": 0.88 },
        "overlap_iou": 0.23,
        "winner_class": "Table",
        "method": "class_priority"
      }
    ]
  },
  "pipeline_info": {
    "tta_enabled": true,
    "tta_views": "3 scales ร— 2 flips โ†’ WBF",
    "model": "Faster R-CNN ResNet-50 FPN v2 (Apache 2.0)",
    "postprocess": "per-class NMS + priority-based overlap arbitration"
  }
}

Web Demo

bash
python src/web/app.py
# Access at http://localhost:7860

Features:

  • โ€”Upload drawing โ†’ instant detection visualization
  • โ€”๐Ÿ”ฌ TTA toggle โ€” enable/disable multi-scale inference on the fly
  • โ€”Confidence threshold slider
  • โ€”๐Ÿ“‹ JSON Output tab โ€” full structured result
  • โ€”๐Ÿ“ OCR Results tab โ€” extracted text from Notes and Tables
  • โ€”๐Ÿ”€ Overlap Resolution tab โ€” resolution log for each detected overlap

Technical Report

Methodology

Detection strategy:

  • โ€”Faster R-CNN (two-stage) was chosen for its precision on complex engineering drawings. One-stage detectors (SSD, FCOS) tend to miss small annotations in dense layouts.
  • โ€”Per-class confidence thresholds account for the severe class imbalance (41 Note annotations vs. 268 PartDrawing).
  • โ€”Custom prefer-larger NMS for the Table class ensures footer title-blocks (low confidence, large area) are not suppressed by partial fragment detections (high confidence, small area).

OCR strategy:

  • โ€”PaddleOCR with angle classification handles rotated text in drawings.
  • โ€”PP-Structure produces HTML table output, preserving row/column alignment for BOM tables.

Experiments conducted

  1. 1.Model comparison: Faster R-CNN vs. RetinaNet vs. SSD. Faster R-CNN achieved highest recall for small Notes.
  2. 2.Augmentation ablation: Adding CLAHE + Perspective reduced validation loss by ~15%.
  3. 3.Oversampling: 4ร— Note oversampling improved Note AP from ~0.61 โ†’ ~0.87.
  4. 4.Copy-Paste: ~+4pp Note AP improvement by generating synthetic training varieties.
  5. 5.TTA: +5โ€“10% recall on held-out test images, particularly for small Notes near drawing edges.

Direction for future improvements

  • โ€”Instance Segmentation (Mask R-CNN): Non-rectangular drawing boundaries for cleaner OCR crops
  • โ€”Domain-specific fine-tuning of PP-Structure: Improve column alignment on faded engineering tables
  • โ€”Confidence calibration (Temperature Scaling): Calibrate raw model logits for better-calibrated confidence scores
  • โ€”RT-DETR ensemble: Combine Transformer-based detector predictions as additional TTA view

License

Detection components: torchvision BSD-3 โ€” commercially compatible. OCR components: PaddleOCR Apache 2.0 โ€” commercially compatible. No AGPL/GPL components used.