Skip to content

Image Pipeline Playground

feat(backend/nodes): add sobel laplacian and bilateral filters

Mohammad Rajaeid4d52a7b12a8
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.py
index c1ea3d3..59926ac 100644
--- a/backend/app/nodes/__init__.py
+++ b/backend/app/nodes/__init__.py
@@ -2,7 +2,15 @@
from app.engine.registry import registry
from app.nodes.color import MergeChannelsNode, SplitChannelsNode, ToGrayNode, ToHsvNode
-from app.nodes.filters import CannyNode, GaussianBlurNode, MedianBlurNode, ThresholdNode
+from app.nodes.filters import (
+ BilateralFilterNode,
+ CannyNode,
+ GaussianBlurNode,
+ LaplacianNode,
+ MedianBlurNode,
+ SobelNode,
+ ThresholdNode,
+)
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
@@ -25,7 +33,10 @@ def register_builtin_nodes() -> None:
MergeChannelsNode(),
GaussianBlurNode(),
MedianBlurNode(),
+ BilateralFilterNode(),
CannyNode(),
+ SobelNode(),
+ LaplacianNode(),
ThresholdNode(),
ErodeNode(),
DilateNode(),
diff --git a/backend/app/nodes/filters.py b/backend/app/nodes/filters.py
index 4f207bd..a1c1069 100644
--- a/backend/app/nodes/filters.py
+++ b/backend/app/nodes/filters.py
@@ -8,7 +8,7 @@ import cv2
import numpy as np
from app.engine.registry import BaseNode
-from app.nodes.common import image_in, image_out, int_param, number_param, require_image
+from app.nodes.common import image_in, image_out, int_param, number_param, require_image, select_param
def _odd(value: int) -> int:
@@ -163,3 +163,157 @@ class ThresholdNode(BaseNode):
f"_, {dst} = cv2.threshold(_gray, {float(params['thresh'])}, "
f"{float(params['maxval'])}, cv2.THRESH_BINARY)",
]
+
+
+def _as_gray(image: np.ndarray) -> np.ndarray:
+ if len(image.shape) == 2:
+ return image
+ if image.shape[2] == 4:
+ return cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
+ return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
+
+
+class BilateralFilterNode(BaseNode):
+ type = "bilateral_filter"
+ label = "Bilateral Filter"
+ category = "filters"
+ description = "Edge-preserving smoothing (useful before segmentation)."
+ ports = [image_in(), image_out()]
+ params = [
+ int_param("d", "Diameter", 9, minimum=1, maximum=15),
+ number_param("sigma_color", "Sigma Color", 75.0, minimum=1.0, maximum=200.0),
+ number_param("sigma_space", "Sigma Space", 75.0, minimum=1.0, maximum=200.0),
+ ]
+
+ 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)
+ return {
+ "image": cv2.bilateralFilter(
+ image,
+ int(params["d"]),
+ float(params["sigma_color"]),
+ float(params["sigma_space"]),
+ )
+ }
+
+ def emit_python(
+ self,
+ node_id: str,
+ params: dict[str, Any],
+ input_vars: dict[str, str],
+ output_vars: dict[str, str],
+ ) -> list[str]:
+ return [
+ f"{output_vars['image']} = cv2.bilateralFilter("
+ f"{input_vars['image']}, {int(params['d'])}, "
+ f"{float(params['sigma_color'])}, {float(params['sigma_space'])})"
+ ]
+
+
+class SobelNode(BaseNode):
+ type = "sobel"
+ label = "Sobel"
+ category = "filters"
+ description = "Sobel gradient magnitude for edge / structure analysis."
+ ports = [image_in(), image_out()]
+ params = [
+ select_param("dx", "Order X", "1", ["0", "1", "2"]),
+ select_param("dy", "Order Y", "0", ["0", "1", "2"]),
+ int_param("ksize", "Kernel Size", 3, minimum=1, maximum=7),
+ number_param("scale", "Scale", 1.0, minimum=0.1, maximum=10.0, step=0.1),
+ ]
+
+ 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]]:
+ gray = _as_gray(require_image(inputs))
+ dx = int(params["dx"])
+ dy = int(params["dy"])
+ if dx == 0 and dy == 0:
+ dx = 1
+ grad = cv2.Sobel(
+ gray,
+ cv2.CV_64F,
+ dx,
+ dy,
+ ksize=_odd(int(params["ksize"])),
+ scale=float(params["scale"]),
+ )
+ return {"image": cv2.convertScaleAbs(grad)}
+
+ 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"]
+ dx = int(params["dx"])
+ dy = int(params["dy"])
+ if dx == 0 and dy == 0:
+ dx = 1
+ ksize = _odd(int(params["ksize"]))
+ return [
+ f"_gray = {src} if len({src}.shape) == 2 else cv2.cvtColor({src}, cv2.COLOR_BGR2GRAY)",
+ (
+ f"_g = cv2.Sobel(_gray, cv2.CV_64F, {dx}, {dy}, "
+ f"ksize={ksize}, scale={float(params['scale'])})"
+ ),
+ f"{dst} = cv2.convertScaleAbs(_g)",
+ ]
+
+
+class LaplacianNode(BaseNode):
+ type = "laplacian"
+ label = "Laplacian"
+ category = "filters"
+ description = "Laplacian operator for zero-crossing / blur detection cues."
+ ports = [image_in(), image_out()]
+ params = [
+ int_param("ksize", "Kernel Size", 3, minimum=1, maximum=31),
+ number_param("scale", "Scale", 1.0, minimum=0.1, maximum=10.0, step=0.1),
+ ]
+
+ 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]]:
+ gray = _as_gray(require_image(inputs))
+ lap = cv2.Laplacian(
+ gray,
+ cv2.CV_64F,
+ ksize=_odd(int(params["ksize"])),
+ scale=float(params["scale"]),
+ )
+ return {"image": cv2.convertScaleAbs(lap)}
+
+ 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"]
+ ksize = _odd(int(params["ksize"]))
+ return [
+ f"_gray = {src} if len({src}.shape) == 2 else cv2.cvtColor({src}, cv2.COLOR_BGR2GRAY)",
+ (
+ f"_l = cv2.Laplacian(_gray, cv2.CV_64F, "
+ f"ksize={ksize}, scale={float(params['scale'])})"
+ ),
+ f"{dst} = cv2.convertScaleAbs(_l)",
+ ]
diff --git a/backend/tests/test_edge_filters.py b/backend/tests/test_edge_filters.py
new file mode 100644
index 0000000..d50dcd9
--- /dev/null
+++ b/backend/tests/test_edge_filters.py
@@ -0,0 +1,39 @@
+"""Tests for edge / enhancement filter nodes."""
+
+from __future__ import annotations
+
+import numpy as np
+
+from app.engine.registry import registry
+from app.nodes import register_builtin_nodes
+
+
+def test_edge_filter_nodes_registered() -> None:
+ register_builtin_nodes()
+ types = {meta.type for meta in registry.list_metadata()}
+ assert {"bilateral_filter", "sobel", "laplacian"}.issubset(types)
+
+
+def test_sobel_produces_gradient_response() -> None:
+ register_builtin_nodes()
+ image = np.zeros((24, 24), dtype=np.uint8)
+ image[:, 12:] = 255
+ result = registry.get("sobel").execute(
+ {"image": image},
+ {"dx": "1", "dy": "0", "ksize": 3, "scale": 1.0},
+ seed=0,
+ )["image"]
+ assert isinstance(result, np.ndarray)
+ assert result.shape == image.shape
+ assert int(result.max()) > 0
+
+
+def test_bilateral_preserves_shape() -> None:
+ register_builtin_nodes()
+ image = np.random.default_rng(0).integers(0, 255, (20, 20, 3), dtype=np.uint8)
+ result = registry.get("bilateral_filter").execute(
+ {"image": image},
+ {"d": 5, "sigma_color": 50.0, "sigma_space": 50.0},
+ seed=0,
+ )["image"]
+ assert result.shape == image.shape
diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.py
index 3880b78..3a055f2 100644
--- a/backend/tests/test_nodes.py
+++ b/backend/tests/test_nodes.py
@@ -20,7 +20,10 @@ def test_builtin_nodes_registered() -> None:
"merge_channels",
"gaussian_blur",
"median_blur",
+ "bilateral_filter",
"canny",
+ "sobel",
+ "laplacian",
"threshold",
"erode",
"dilate",