Skip to content

Image Pipeline Playground

feat(backend/nodes): add moments analysis node

Mohammad Rajaeif3716c1be218
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.py
index 7e0c5cf..90d05bb 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 ConvexHullNode, FindContoursNode
+from app.nodes.structure import ConvexHullNode, FindContoursNode, ImageMomentsNode
_REGISTERED = False
@@ -62,6 +62,7 @@ def register_builtin_nodes() -> None:
HistogramEqualizeNode(),
FindContoursNode(),
ConvexHullNode(),
+ ImageMomentsNode(),
ErodeNode(),
DilateNode(),
MorphologyExNode(),
diff --git a/backend/app/nodes/structure.py b/backend/app/nodes/structure.py
index ccd3e70..ec56d5d 100644
--- a/backend/app/nodes/structure.py
+++ b/backend/app/nodes/structure.py
@@ -157,7 +157,10 @@ class ConvexHullNode(BaseNode):
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)
+ if str(params["overlay"]) == "blank":
+ canvas = np.zeros_like(_as_bgr(image))
+ else:
+ canvas = _as_bgr(image)
for contour in contours:
if len(contour) < 3:
continue
@@ -194,3 +197,84 @@ class ConvexHullNode(BaseNode):
" _hull = cv2.convexHull(_c)",
f" cv2.drawContours({dst}, [_hull], -1, (255, 160, 0), {int(params['thickness'])})",
]
+
+
+class ImageMomentsNode(BaseNode):
+ type = "moments"
+ label = "Moments"
+ category = "analysis"
+ description = "Draw contour centroids and orientation from spatial moments."
+ ports = [image_in(), image_out()]
+ params = [
+ int_param("min_area", "Min Area", 20, minimum=1, maximum=100000),
+ 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"])
+ for contour in contours:
+ area = cv2.contourArea(contour)
+ if area < min_area:
+ continue
+ moments = cv2.moments(contour)
+ if abs(moments["m00"]) < 1e-6:
+ continue
+ cx = int(moments["m10"] / moments["m00"])
+ cy = int(moments["m01"] / moments["m00"])
+ cv2.circle(canvas, (cx, cy), 4, (0, 200, 255), -1)
+ cv2.drawContours(canvas, [contour], -1, (80, 180, 255), 1)
+ # Orientation from central moments / covariance.
+ mu20 = moments["mu20"] / moments["m00"]
+ mu02 = moments["mu02"] / moments["m00"]
+ mu11 = moments["mu11"] / moments["m00"]
+ angle = 0.5 * np.arctan2(2 * mu11, mu20 - mu02)
+ length = max(12.0, np.sqrt(area) * 0.35)
+ dx = int(length * np.cos(angle))
+ dy = int(length * np.sin(angle))
+ cv2.line(canvas, (cx - dx, cy - dy), (cx + dx, cy + dy), (0, 255, 180), 2)
+ 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",
+ " _m = cv2.moments(_c)",
+ " if abs(_m['m00']) < 1e-6: continue",
+ " _cx = int(_m['m10'] / _m['m00']); _cy = int(_m['m01'] / _m['m00'])",
+ f" cv2.circle({dst}, (_cx, _cy), 4, (0, 200, 255), -1)",
+ f" cv2.drawContours({dst}, [_c], -1, (80, 180, 255), 1)",
+ ]
diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.py
index d8999b8..051b3cf 100644
--- a/backend/tests/test_nodes.py
+++ b/backend/tests/test_nodes.py
@@ -34,6 +34,7 @@ def test_builtin_nodes_registered() -> None:
"histogram_equalize",
"find_contours",
"convex_hull",
+ "moments",
"erode",
"dilate",
"morphology_ex",
diff --git a/backend/tests/test_structure_moments.py b/backend/tests/test_structure_moments.py
new file mode 100644
index 0000000..8aac583
--- /dev/null
+++ b/backend/tests/test_structure_moments.py
@@ -0,0 +1,28 @@
+"""Tests for moments 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_moments_registered() -> None:
+ register_builtin_nodes()
+ assert "moments" in {meta.type for meta in registry.list_metadata()}
+
+
+def test_moments_draws_centroid_for_blob() -> None:
+ register_builtin_nodes()
+ image = np.zeros((64, 64), dtype=np.uint8)
+ image[20:44, 20:44] = 255
+ result = registry.get("moments").execute(
+ {"image": image},
+ {"min_area": 20, "overlay": "blank"},
+ seed=0,
+ )["image"]
+ assert result.ndim == 3
+ assert int(result.sum()) > 0
+ # Centroid marker near image center should light up.
+ assert int(result[30:34, 30:34].sum()) > 0