Spaces:
Sleeping
Sleeping
Commit
·
b2a84cb
1
Parent(s):
b4d1348
superpoint refactored
Browse files
backend/py/app/inference/dl_adapters/__init__.py
CHANGED
|
@@ -5,7 +5,7 @@ import os
|
|
| 5 |
from .base import AdapterContext, DLAdapter
|
| 6 |
from .dexined import DexiNedAdapter
|
| 7 |
from .edges import EdgesAdapter
|
| 8 |
-
from .superpoint import SuperPointAdapter
|
| 9 |
|
| 10 |
|
| 11 |
def get_adapter(model_path: str, detector: str) -> DLAdapter:
|
|
@@ -13,7 +13,7 @@ def get_adapter(model_path: str, detector: str) -> DLAdapter:
|
|
| 13 |
if "dexined" in name:
|
| 14 |
return DexiNedAdapter()
|
| 15 |
if "superpoint" in name or (detector.startswith("Corners") and "super" in name):
|
| 16 |
-
return
|
| 17 |
if any(k in name for k in ("hed",)) or detector.startswith("Edges"):
|
| 18 |
return EdgesAdapter()
|
| 19 |
return EdgesAdapter()
|
|
@@ -25,5 +25,6 @@ __all__ = [
|
|
| 25 |
"DexiNedAdapter",
|
| 26 |
"EdgesAdapter",
|
| 27 |
"SuperPointAdapter",
|
|
|
|
| 28 |
"get_adapter",
|
| 29 |
]
|
|
|
|
| 5 |
from .base import AdapterContext, DLAdapter
|
| 6 |
from .dexined import DexiNedAdapter
|
| 7 |
from .edges import EdgesAdapter
|
| 8 |
+
from .superpoint import SuperPointAdapter, SuperPointTransformersAdapter
|
| 9 |
|
| 10 |
|
| 11 |
def get_adapter(model_path: str, detector: str) -> DLAdapter:
|
|
|
|
| 13 |
if "dexined" in name:
|
| 14 |
return DexiNedAdapter()
|
| 15 |
if "superpoint" in name or (detector.startswith("Corners") and "super" in name):
|
| 16 |
+
return SuperPointTransformersAdapter()
|
| 17 |
if any(k in name for k in ("hed",)) or detector.startswith("Edges"):
|
| 18 |
return EdgesAdapter()
|
| 19 |
return EdgesAdapter()
|
|
|
|
| 25 |
"DexiNedAdapter",
|
| 26 |
"EdgesAdapter",
|
| 27 |
"SuperPointAdapter",
|
| 28 |
+
"SuperPointTransformersAdapter",
|
| 29 |
"get_adapter",
|
| 30 |
]
|
requirements.txt
CHANGED
|
@@ -4,3 +4,5 @@ numpy>=1.26.0
|
|
| 4 |
fastapi>=0.112.0
|
| 5 |
uvicorn>=0.30.0
|
| 6 |
python-multipart>=0.0.9
|
|
|
|
|
|
|
|
|
| 4 |
fastapi>=0.112.0
|
| 5 |
uvicorn>=0.30.0
|
| 6 |
python-multipart>=0.0.9
|
| 7 |
+
transformers>=4.57.0
|
| 8 |
+
Pillow>=10.0.0
|
tests/test_superpoint_consistency.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
# Ensure project root is available on sys.path when tests run directly.
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
if str(ROOT) not in sys.path:
|
| 11 |
+
sys.path.insert(0, str(ROOT))
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import onnxruntime as ort # type: ignore
|
| 15 |
+
except ImportError: # pragma: no cover - dependency managed by test skip
|
| 16 |
+
ort = None # type: ignore
|
| 17 |
+
|
| 18 |
+
from backend.py.app.inference.dl_adapters.superpoint import (
|
| 19 |
+
SuperPointAdapter,
|
| 20 |
+
SuperPointTransformersAdapter,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import torch
|
| 25 |
+
except ImportError: # pragma: no cover - dependency managed by test skips
|
| 26 |
+
torch = None # type: ignore
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _synthetic_corner_image(size: int = 256) -> np.ndarray:
|
| 30 |
+
img = np.zeros((size, size, 3), dtype=np.uint8)
|
| 31 |
+
cv2.rectangle(img, (size // 8, size // 8), (7 * size // 8, 7 * size // 8), (255, 255, 255), thickness=3)
|
| 32 |
+
cv2.line(img, (size // 8, size // 8), (7 * size // 8, 7 * size // 8), (255, 255, 255), thickness=2)
|
| 33 |
+
cv2.line(img, (size // 8, 7 * size // 8), (7 * size // 8, size // 8), (255, 255, 255), thickness=2)
|
| 34 |
+
cv2.circle(img, (size // 2, size // 2), size // 4, (255, 255, 255), thickness=2)
|
| 35 |
+
return img
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _normalized_heatmap(heat: np.ndarray) -> np.ndarray:
|
| 39 |
+
heat_min = float(np.min(heat))
|
| 40 |
+
heat_max = float(np.max(heat))
|
| 41 |
+
eps = 1e-8
|
| 42 |
+
return (heat - heat_min) / (heat_max - heat_min + eps)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@pytest.mark.skipif(ort is None, reason="onnxruntime is required for SuperPoint ONNX comparison")
|
| 46 |
+
@pytest.mark.xfail(
|
| 47 |
+
reason="Current superpoint.onnx export diverges from the transformers reference implementation",
|
| 48 |
+
strict=True,
|
| 49 |
+
)
|
| 50 |
+
def test_superpoint_onnx_matches_transformers_heatmap():
|
| 51 |
+
model_path = ROOT / "models" / "superpoint.onnx"
|
| 52 |
+
if not model_path.is_file():
|
| 53 |
+
pytest.skip("superpoint.onnx model not available in ./models directory")
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
hf_adapter = SuperPointTransformersAdapter(device="cpu")
|
| 57 |
+
except ImportError as exc: # pragma: no cover - dependency checked by skip
|
| 58 |
+
pytest.skip(str(exc))
|
| 59 |
+
if torch is None: # pragma: no cover - dependency checked by skip
|
| 60 |
+
pytest.skip("PyTorch is required for the transformers comparison test")
|
| 61 |
+
|
| 62 |
+
sess = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])
|
| 63 |
+
onnx_adapter = SuperPointAdapter()
|
| 64 |
+
|
| 65 |
+
image = _synthetic_corner_image()
|
| 66 |
+
|
| 67 |
+
feed_onnx, ctx_onnx = onnx_adapter.preprocess(image, sess)
|
| 68 |
+
outputs_onnx = sess.run(None, feed_onnx)
|
| 69 |
+
semi_onnx, _ = onnx_adapter._pick_outputs(outputs_onnx)
|
| 70 |
+
heat_onnx = onnx_adapter._semi_to_heat(semi_onnx)
|
| 71 |
+
heat_onnx = cv2.resize(heat_onnx, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_CUBIC)
|
| 72 |
+
heat_onnx = _normalized_heatmap(heat_onnx)
|
| 73 |
+
|
| 74 |
+
feed_hf, ctx_hf = hf_adapter.preprocess(image, None)
|
| 75 |
+
outputs_hf = hf_adapter._forward(feed_hf[hf_adapter._PIXEL_VALUES_KEY])
|
| 76 |
+
mask = outputs_hf.mask[0] if outputs_hf.mask is not None else torch.ones_like(outputs_hf.scores[0], dtype=torch.bool)
|
| 77 |
+
mask = mask.bool()
|
| 78 |
+
keypoints = outputs_hf.keypoints[0][mask]
|
| 79 |
+
scores = outputs_hf.scores[0][mask]
|
| 80 |
+
|
| 81 |
+
heat_hf = np.zeros_like(heat_onnx)
|
| 82 |
+
keypoints_np = keypoints.detach().cpu().numpy()
|
| 83 |
+
scores_np = scores.detach().cpu().numpy()
|
| 84 |
+
H, W = image.shape[:2]
|
| 85 |
+
for (x_rel, y_rel), score in zip(keypoints_np, scores_np):
|
| 86 |
+
x = int(round(float(np.clip(x_rel * (W - 1), 0, W - 1))))
|
| 87 |
+
y = int(round(float(np.clip(y_rel * (H - 1), 0, H - 1))))
|
| 88 |
+
heat_hf[y, x] = max(heat_hf[y, x], float(score))
|
| 89 |
+
heat_hf = _normalized_heatmap(heat_hf)
|
| 90 |
+
|
| 91 |
+
correlation = np.corrcoef(heat_onnx.flatten(), heat_hf.flatten())[0, 1]
|
| 92 |
+
mean_absolute_error = float(np.mean(np.abs(heat_onnx - heat_hf)))
|
| 93 |
+
|
| 94 |
+
_, meta_onnx = onnx_adapter.postprocess(outputs_onnx, image, ctx_onnx, "Corners (SuperPoint)")
|
| 95 |
+
_, meta_hf = hf_adapter.postprocess(outputs_hf, image, ctx_hf, "Corners (SuperPoint)")
|
| 96 |
+
|
| 97 |
+
assert correlation > 0.9
|
| 98 |
+
assert mean_absolute_error < 0.05
|
| 99 |
+
assert meta_onnx["num_corners"] == pytest.approx(meta_hf["num_keypoints"], rel=0.1, abs=10)
|
| 100 |
+
assert meta_onnx["heat_mean"] == pytest.approx(meta_hf["scores_mean"], rel=0.1, abs=1e-3)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@pytest.mark.skipif(torch is None, reason="PyTorch is required for the transformers adapter test")
|
| 104 |
+
def test_superpoint_transformers_adapter_infer_returns_overlay_and_meta():
|
| 105 |
+
try:
|
| 106 |
+
adapter = SuperPointTransformersAdapter(device="cpu")
|
| 107 |
+
except ImportError as exc: # pragma: no cover - dependency checked by skip
|
| 108 |
+
pytest.skip(str(exc))
|
| 109 |
+
|
| 110 |
+
image = _synthetic_corner_image()
|
| 111 |
+
overlay, meta = adapter.infer(image, detector="Corners (SuperPoint)")
|
| 112 |
+
|
| 113 |
+
assert overlay.shape == image.shape
|
| 114 |
+
assert overlay.dtype == np.uint8
|
| 115 |
+
assert meta["adapter"] == "superpoint_transformers"
|
| 116 |
+
assert meta["backend"] == "transformers"
|
| 117 |
+
assert isinstance(meta["num_keypoints"], int)
|
| 118 |
+
assert meta["descriptors_shape"] is None or meta["descriptors_shape"][1] == 256
|