Skip to content

Image Pipeline Playground

feat(backend/nodes): add approx poly analysis node

Mohammad Rajaei12727025e6af
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.py
index 31d5f8b..890efc3 100644
--- a/backend/app/nodes/__init__.py
+++ b/backend/app/nodes/__init__.py
@@ -30,6 +30,7 @@ from app.nodes.io import LoadImageNode, PreviewNode, SaveImageNode
from app.nodes.morphology import DilateNode, ErodeNode, MorphologyExNode
from app.nodes.stochastic import GaussianNoiseNode, RandomBrightnessContrastNode
from app.nodes.structure import (
+ ApproxPolyNode,
BlobDetectNode,
BoundingRectNode,
ConnectedComponentsNode,
@@ -73,6 +74,7 @@ def register_builtin_nodes() -> None:
ConnectedComponentsNode(),
BlobDetectNode(),
BoundingRectNode(),
+ ApproxPolyNode(),
ErodeNode(),
DilateNode(),
MorphologyExNode(),
diff --git a/backend/app/nodes/structure.py b/backend/app/nodes/structure.py
index f5615b4..e900dba 100644
--- a/backend/app/nodes/structure.py
+++ b/backend/app/nodes/structure.py
@@ -591,3 +591,86 @@ class BoundingRectNode(BaseNode):
]
)
return lines
+
+
+class ApproxPolyNode(BaseNode):
+ type = "approx_poly"
+ label = "Approx Poly"
+ category = "analysis"
+ description = "Approximate contours with polygons (Douglas-Peucker)."
+ ports = [image_in(), image_out()]
+ params = [
+ number_param(
+ "epsilon",
+ "Epsilon Ratio",
+ 0.02,
+ minimum=0.001,
+ maximum=0.5,
+ step=0.001,
+ description="Approximation accuracy as a fraction of contour perimeter.",
+ ),
+ int_param("min_area", "Min Area", 20, minimum=1, maximum=100000),
+ int_param("thickness", "Thickness", 2, minimum=1, maximum=10),
+ select_param("overlay", "Overlay", "on_input", ["on_input", "blank"]),
+ ]
+
+ def execute(
+ self,
+ inputs: dict[str, np.ndarray | list[np.ndarray] | None],
+ params: dict[str, Any],
+ seed: int = 0,
+ ) -> dict[str, np.ndarray | list[np.ndarray]]:
+ image = require_image(inputs)
+ binary = _binary(image)
+ contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
+ if str(params["overlay"]) == "blank":
+ canvas = np.zeros_like(_as_bgr(image))
+ else:
+ canvas = _as_bgr(image)
+ min_area = float(params["min_area"])
+ epsilon_ratio = float(params["epsilon"])
+ thickness = int(params["thickness"])
+ for contour in contours:
+ if cv2.contourArea(contour) < min_area:
+ continue
+ peri = cv2.arcLength(contour, True)
+ approx = cv2.approxPolyDP(contour, epsilon_ratio * peri, True)
+ cv2.drawContours(canvas, [approx], -1, (180, 80, 255), thickness)
+ for point in approx:
+ x, y = point.ravel()
+ cv2.circle(canvas, (int(x), int(y)), 3, (255, 220, 80), -1)
+ return {"image": canvas}
+
+ def emit_python(
+ self,
+ node_id: str,
+ params: dict[str, Any],
+ input_vars: dict[str, str],
+ output_vars: dict[str, str],
+ ) -> list[str]:
+ src = input_vars["image"]
+ dst = output_vars["image"]
+ blank = str(params["overlay"]) == "blank"
+ return [
+ f"_gray = {src} if len({src}.shape) == 2 else cv2.cvtColor({src}, cv2.COLOR_BGR2GRAY)",
+ "_uniq = set(np.unique(_gray).tolist())",
+ "_bin = _gray if _uniq <= {0, 255} else "
+ "cv2.threshold(_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]",
+ "_cnts, _ = cv2.findContours(_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)",
+ (
+ f"{dst} = np.zeros((_gray.shape[0], _gray.shape[1], 3), dtype='uint8')"
+ if blank
+ else (
+ f"{dst} = {src}.copy() if len({src}.shape) == 3 else "
+ f"cv2.cvtColor({src}, cv2.COLOR_GRAY2BGR)"
+ )
+ ),
+ "for _c in _cnts:",
+ f" if cv2.contourArea(_c) < {float(params['min_area'])}: continue",
+ " _peri = cv2.arcLength(_c, True)",
+ f" _ap = cv2.approxPolyDP(_c, {float(params['epsilon'])} * _peri, True)",
+ f" cv2.drawContours({dst}, [_ap], -1, (180, 80, 255), {int(params['thickness'])})",
+ " for _p in _ap:",
+ " _x, _y = _p.ravel()",
+ f" cv2.circle({dst}, (int(_x), int(_y)), 3, (255, 220, 80), -1)",
+ ]
diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.py
index 2f478d2..f660bd6 100644
--- a/backend/tests/test_nodes.py
+++ b/backend/tests/test_nodes.py
@@ -38,6 +38,7 @@ def test_builtin_nodes_registered() -> None:
"connected_components",
"blob_detect",
"bounding_rect",
+ "approx_poly",
"erode",
"dilate",
"morphology_ex",
diff --git a/backend/tests/test_structure_approx.py b/backend/tests/test_structure_approx.py
new file mode 100644
index 0000000..a7776cc
--- /dev/null
+++ b/backend/tests/test_structure_approx.py
@@ -0,0 +1,26 @@
+"""Tests for approx-poly structure node."""
+
+from __future__ import annotations
+
+import numpy as np
+
+from app.engine.registry import registry
+from app.nodes import register_builtin_nodes
+
+
+def test_approx_poly_registered() -> None:
+ register_builtin_nodes()
+ assert "approx_poly" in {meta.type for meta in registry.list_metadata()}
+
+
+def test_approx_poly_draws_for_rectangle() -> None:
+ register_builtin_nodes()
+ image = np.zeros((64, 64), dtype=np.uint8)
+ image[12:52, 16:48] = 255
+ result = registry.get("approx_poly").execute(
+ {"image": image},
+ {"epsilon": 0.02, "min_area": 10, "thickness": 2, "overlay": "blank"},
+ seed=0,
+ )["image"]
+ assert result.ndim == 3
+ assert int(result.sum()) > 0