Image Pipeline Playground
feat(backend/nodes): add bounding rect analysis node
Mohammad Rajaeie2a3eb7eb5a0
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.pyindex aadf5fd..31d5f8b 100644--- a/backend/app/nodes/__init__.py+++ b/backend/app/nodes/__init__.py@@ -31,6 +31,7 @@ from app.nodes.morphology import DilateNode, ErodeNode, MorphologyExNodefrom app.nodes.stochastic import GaussianNoiseNode, RandomBrightnessContrastNodefrom app.nodes.structure import (BlobDetectNode,+ BoundingRectNode,ConnectedComponentsNode,ConvexHullNode,FindContoursNode,@@ -71,6 +72,7 @@ def register_builtin_nodes() -> None:ImageMomentsNode(),ConnectedComponentsNode(),BlobDetectNode(),+ BoundingRectNode(),ErodeNode(),DilateNode(),MorphologyExNode(),diff --git a/backend/app/nodes/structure.py b/backend/app/nodes/structure.pyindex 01c70fe..f5615b4 100644--- a/backend/app/nodes/structure.py+++ b/backend/app/nodes/structure.py@@ -500,3 +500,94 @@ class BlobDetectNode(BaseNode):"cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)"),]+++class BoundingRectNode(BaseNode):+ type = "bounding_rect"+ label = "Bounding Rect"+ category = "analysis"+ description = "Draw axis-aligned or rotated bounding rectangles for contours."+ ports = [image_in(), image_out()]+ params = [+ select_param("kind", "Kind", "axis", ["axis", "rotated"]),+ 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"])+ thickness = int(params["thickness"])+ rotated = str(params["kind"]) == "rotated"+ for contour in contours:+ if cv2.contourArea(contour) < min_area:+ continue+ if rotated:+ rect = cv2.minAreaRect(contour)+ box = np.int32(cv2.boxPoints(rect))+ cv2.drawContours(canvas, [box], 0, (255, 80, 80), thickness)+ else:+ x, y, w, h = cv2.boundingRect(contour)+ cv2.rectangle(canvas, (x, y), (x + w - 1, y + h - 1), (255, 80, 80), 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"+ thickness = int(params["thickness"])+ min_area = float(params["min_area"])+ rotated = str(params["kind"]) == "rotated"+ lines = [+ 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) < {min_area}: continue",+ ]+ if rotated:+ lines.extend(+ [+ " _box = np.int32(cv2.boxPoints(cv2.minAreaRect(_c)))",+ f" cv2.drawContours({dst}, [_box], 0, (255, 80, 80), {thickness})",+ ]+ )+ else:+ lines.extend(+ [+ " _x, _y, _w, _h = cv2.boundingRect(_c)",+ (+ f" cv2.rectangle({dst}, (_x, _y), (_x+_w-1, _y+_h-1), "+ f"(255, 80, 80), {thickness})"+ ),+ ]+ )+ return linesdiff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.pyindex d23b210..2f478d2 100644--- a/backend/tests/test_nodes.py+++ b/backend/tests/test_nodes.py@@ -37,6 +37,7 @@ def test_builtin_nodes_registered() -> None:"moments","connected_components","blob_detect",+ "bounding_rect","erode","dilate","morphology_ex",diff --git a/backend/tests/test_structure_rect.py b/backend/tests/test_structure_rect.pynew file mode 100644index 0000000..1674d03--- /dev/null+++ b/backend/tests/test_structure_rect.py@@ -0,0 +1,39 @@+"""Tests for bounding-rect 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_bounding_rect_registered() -> None:+ register_builtin_nodes()+ assert "bounding_rect" in {meta.type for meta in registry.list_metadata()}+++def test_bounding_rect_axis_draws() -> None:+ register_builtin_nodes()+ image = np.zeros((64, 64), dtype=np.uint8)+ image[16:48, 20:44] = 255+ result = registry.get("bounding_rect").execute(+ {"image": image},+ {"kind": "axis", "min_area": 10, "thickness": 2, "overlay": "blank"},+ seed=0,+ )["image"]+ assert result.ndim == 3+ assert int(result.sum()) > 0+++def test_bounding_rect_rotated_draws() -> None:+ register_builtin_nodes()+ image = np.zeros((64, 64), dtype=np.uint8)+ image[16:48, 20:44] = 255+ result = registry.get("bounding_rect").execute(+ {"image": image},+ {"kind": "rotated", "min_area": 10, "thickness": 2, "overlay": "blank"},+ seed=0,+ )["image"]+ assert result.ndim == 3+ assert int(result.sum()) > 0