Skip to content

Image Pipeline Playground

feat(backend/nodes): add convex hull analysis node

Mohammad Rajaei2a633e511568
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.py
index ef09db5..7e0c5cf 100644
--- a/backend/app/nodes/__init__.py
+++ b/backend/app/nodes/__init__.py
@@ -29,7 +29,7 @@ from app.nodes.geometry import CropNode, FlipNode, ResizeNode, RotateNode
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 FindContoursNode
+from app.nodes.structure import ConvexHullNode, FindContoursNode
_REGISTERED = False
@@ -61,6 +61,7 @@ def register_builtin_nodes() -> None:
DistanceTransformNode(),
HistogramEqualizeNode(),
FindContoursNode(),
+ ConvexHullNode(),
ErodeNode(),
DilateNode(),
MorphologyExNode(),
diff --git a/backend/app/nodes/structure.py b/backend/app/nodes/structure.py
index cfeab41..ccd3e70 100644
--- a/backend/app/nodes/structure.py
+++ b/backend/app/nodes/structure.py
@@ -135,3 +135,62 @@ class FindContoursNode(BaseNode):
),
f"cv2.drawContours({dst}, _cnts, -1, (0, 255, 128), {int(params['thickness'])})",
]
+
+
+class ConvexHullNode(BaseNode):
+ type = "convex_hull"
+ label = "Convex Hull"
+ category = "analysis"
+ description = "Compute and draw convex hulls for each external contour."
+ ports = [image_in(), image_out()]
+ params = [
+ 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)
+ canvas = np.zeros_like(_as_bgr(image)) if str(params["overlay"]) == "blank" else _as_bgr(image)
+ for contour in contours:
+ if len(contour) < 3:
+ continue
+ hull = cv2.convexHull(contour)
+ cv2.drawContours(canvas, [hull], -1, (255, 160, 0), int(params["thickness"]))
+ 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:",
+ " if len(_c) < 3: continue",
+ " _hull = cv2.convexHull(_c)",
+ f" cv2.drawContours({dst}, [_hull], -1, (255, 160, 0), {int(params['thickness'])})",
+ ]
diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.py
index 64c39d4..d8999b8 100644
--- a/backend/tests/test_nodes.py
+++ b/backend/tests/test_nodes.py
@@ -33,6 +33,7 @@ def test_builtin_nodes_registered() -> None:
"distance_transform",
"histogram_equalize",
"find_contours",
+ "convex_hull",
"erode",
"dilate",
"morphology_ex",
diff --git a/backend/tests/test_structure_hull.py b/backend/tests/test_structure_hull.py
new file mode 100644
index 0000000..db203f2
--- /dev/null
+++ b/backend/tests/test_structure_hull.py
@@ -0,0 +1,27 @@
+"""Tests for convex hull 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_convex_hull_registered() -> None:
+ register_builtin_nodes()
+ assert "convex_hull" in {meta.type for meta in registry.list_metadata()}
+
+
+def test_convex_hull_draws_for_l_shape() -> None:
+ register_builtin_nodes()
+ image = np.zeros((60, 60), dtype=np.uint8)
+ image[10:50, 10:20] = 255
+ image[40:50, 10:50] = 255
+ result = registry.get("convex_hull").execute(
+ {"image": image},
+ {"thickness": 2, "overlay": "blank"},
+ seed=0,
+ )["image"]
+ assert result.ndim == 3
+ assert int(result.sum()) > 0