Image Pipeline Playground
feat(backend/nodes): add bitwise, absdiff, blend, and arithmetic nodes
Mohammad Rajaeib8fd2864a6cb
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.pyindex ff1d037..7aae365 100644--- a/backend/app/nodes/__init__.py+++ b/backend/app/nodes/__init__.py@@ -39,7 +39,13 @@ from app.nodes.filters import ()from app.nodes.geometry import CropNode, FlipNode, ResizeNode, RotateNodefrom app.nodes.io import BlankImageNode, LoadImageNode, PreviewNode, SaveImageNode-from app.nodes.math import ApplyMaskNode+from app.nodes.math import (+ AbsDiffNode,+ AddWeightedNode,+ ApplyMaskNode,+ ArithmeticNode,+ BitwiseNode,+)from app.nodes.morphology import DilateNode, ErodeNode, MorphologyExNodefrom app.nodes.stochastic import GaussianNoiseNode, RandomBrightnessContrastNodefrom app.nodes.structure import (@@ -78,6 +84,10 @@ def register_builtin_nodes() -> None:MergeChannelsNode(),InRangeNode(),ApplyMaskNode(),+ BitwiseNode(),+ AbsDiffNode(),+ AddWeightedNode(),+ ArithmeticNode(),GaussianBlurNode(),MedianBlurNode(),BoxBlurNode(),diff --git a/backend/app/nodes/math.py b/backend/app/nodes/math.pyindex 2480f05..1a09f00 100644--- a/backend/app/nodes/math.py+++ b/backend/app/nodes/math.py@@ -116,8 +116,14 @@ class ApplyMaskNode(BaseNode):dst = output_vars["image"]fill = str(params["fill"])lines = [- f"_mask = {mask} if len({mask}.shape) == 2 else cv2.cvtColor({mask}, cv2.COLOR_BGR2GRAY)",- f"_mask = cv2.resize(_mask, ({src}.shape[1], {src}.shape[0]), interpolation=cv2.INTER_NEAREST)",+ (+ f"_mask = {mask} if len({mask}.shape) == 2 else "+ f"cv2.cvtColor({mask}, cv2.COLOR_BGR2GRAY)"+ ),+ (+ f"_mask = cv2.resize(_mask, ({src}.shape[1], {src}.shape[0]), "+ "interpolation=cv2.INTER_NEAREST)"+ ),]if fill == "unchanged":lines.append(f"{dst} = {src}.copy()")@@ -126,10 +132,206 @@ class ApplyMaskNode(BaseNode):[f"_kept = cv2.bitwise_and({src}, {src}, mask=_mask)","_inv = cv2.bitwise_not(_mask)",- f"_bg = cv2.bitwise_and(np.full_like({src}, 255), np.full_like({src}, 255), mask=_inv)",+ (+ f"_bg = cv2.bitwise_and(np.full_like({src}, 255), "+ f"np.full_like({src}, 255), mask=_inv)"+ ),f"{dst} = cv2.add(_kept, _bg)",])else:lines.append(f"{dst} = cv2.bitwise_and({src}, {src}, mask=_mask)")return lines+++class BitwiseNode(BaseNode):+ type = "bitwise"+ label = "Bitwise"+ category = "math"+ description = "Bitwise AND / OR / XOR between two images, with optional mask."+ ports = [+ image_in("a", "Image A"),+ image_in("b", "Image B"),+ image_in("mask", "Mask", optional=True),+ image_out(),+ ]+ params = [+ select_param("op", "Operation", "and", ["and", "or", "xor"]),+ ]++ 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]]:+ a, b = _align_pair(require_image(inputs, "a"), require_image(inputs, "b"))+ mask = _optional_mask(inputs, a.shape[:2])+ op = str(params["op"])+ if op == "or":+ result = cv2.bitwise_or(a, b, mask=mask)+ elif op == "xor":+ result = cv2.bitwise_xor(a, b, mask=mask)+ else:+ result = cv2.bitwise_and(a, b, mask=mask)+ return {"image": result}++ def emit_python(+ self,+ node_id: str,+ params: dict[str, Any],+ input_vars: dict[str, str],+ output_vars: dict[str, str],+ ) -> list[str]:+ op = str(params["op"])+ fn = {"and": "bitwise_and", "or": "bitwise_or", "xor": "bitwise_xor"}.get(+ op, "bitwise_and"+ )+ a = input_vars["a"]+ b = input_vars["b"]+ dst = output_vars["image"]+ if "mask" in input_vars:+ return [+ f"{dst} = cv2.{fn}({a}, {b}, mask={input_vars['mask']})",+ ]+ return [f"{dst} = cv2.{fn}({a}, {b})"]+++class AbsDiffNode(BaseNode):+ type = "absdiff"+ label = "Abs Diff"+ category = "math"+ description = "Absolute per-pixel difference between two images."+ ports = [+ image_in("a", "Image A"),+ image_in("b", "Image B"),+ image_out(),+ ]+ params = []++ 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]]:+ a, b = _align_pair(require_image(inputs, "a"), require_image(inputs, "b"))+ return {"image": cv2.absdiff(a, b)}++ 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.absdiff({input_vars['a']}, {input_vars['b']})"+ ]+++class AddWeightedNode(BaseNode):+ type = "add_weighted"+ label = "Add Weighted"+ category = "math"+ description = "Blend two images: alpha*A + beta*B + gamma."+ ports = [+ image_in("a", "Image A"),+ image_in("b", "Image B"),+ image_out(),+ ]+ params = [+ number_param("alpha", "Alpha (A)", 0.5, minimum=0.0, maximum=2.0, step=0.05),+ number_param("beta", "Beta (B)", 0.5, minimum=0.0, maximum=2.0, step=0.05),+ number_param("gamma", "Gamma", 0.0, minimum=-100.0, maximum=100.0, step=1.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]]:+ a, b = _align_pair(require_image(inputs, "a"), require_image(inputs, "b"))+ return {+ "image": cv2.addWeighted(+ a,+ float(params["alpha"]),+ b,+ float(params["beta"]),+ float(params["gamma"]),+ )+ }++ 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.addWeighted("+ f"{input_vars['a']}, {float(params['alpha'])}, "+ f"{input_vars['b']}, {float(params['beta'])}, "+ f"{float(params['gamma'])})"+ )+ ]+++class ArithmeticNode(BaseNode):+ type = "arithmetic"+ label = "Arithmetic"+ category = "math"+ description = "Saturated add / subtract / multiply of two images."+ ports = [+ image_in("a", "Image A"),+ image_in("b", "Image B"),+ image_in("mask", "Mask", optional=True),+ image_out(),+ ]+ params = [+ select_param("op", "Operation", "add", ["add", "subtract", "multiply"]),+ ]++ 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]]:+ a, b = _align_pair(require_image(inputs, "a"), require_image(inputs, "b"))+ mask = _optional_mask(inputs, a.shape[:2])+ op = str(params["op"])+ if op == "subtract":+ result = cv2.subtract(a, b, mask=mask)+ elif op == "multiply":+ result = cv2.multiply(a, b)+ if mask is not None:+ result = cv2.bitwise_and(result, result, mask=mask)+ else:+ result = cv2.add(a, b, mask=mask)+ return {"image": result}++ def emit_python(+ self,+ node_id: str,+ params: dict[str, Any],+ input_vars: dict[str, str],+ output_vars: dict[str, str],+ ) -> list[str]:+ op = str(params["op"])+ a = input_vars["a"]+ b = input_vars["b"]+ dst = output_vars["image"]+ mask = input_vars.get("mask")+ if op == "multiply":+ lines = [f"{dst} = cv2.multiply({a}, {b})"]+ if mask:+ lines.append(f"{dst} = cv2.bitwise_and({dst}, {dst}, mask={mask})")+ return lines+ fn = "subtract" if op == "subtract" else "add"+ if mask:+ return [f"{dst} = cv2.{fn}({a}, {b}, mask={mask})"]+ return [f"{dst} = cv2.{fn}({a}, {b})"]diff --git a/backend/tests/test_math_ops.py b/backend/tests/test_math_ops.pynew file mode 100644index 0000000..84b9dec--- /dev/null+++ b/backend/tests/test_math_ops.py@@ -0,0 +1,73 @@+"""Tests for bitwise / arithmetic math nodes."""++from __future__ import annotations++import numpy as np++from app.engine.registry import registry+from app.nodes import register_builtin_nodes+++def test_math_ops_registered() -> None:+ register_builtin_nodes()+ types = {meta.type for meta in registry.list_metadata()}+ assert {"bitwise", "absdiff", "add_weighted", "arithmetic"} <= types+++def test_bitwise_and() -> None:+ register_builtin_nodes()+ a = np.full((4, 4, 3), 200, dtype=np.uint8)+ b = np.full((4, 4, 3), 100, dtype=np.uint8)+ result = registry.get("bitwise").execute(+ {"a": a, "b": b, "mask": None},+ {"op": "and"},+ seed=0,+ )["image"]+ assert tuple(result[0, 0]) == (64, 64, 64) # 200 & 100+++def test_bitwise_with_mask() -> None:+ register_builtin_nodes()+ a = np.full((4, 4, 3), 255, dtype=np.uint8)+ b = np.full((4, 4, 3), 255, dtype=np.uint8)+ mask = np.zeros((4, 4), dtype=np.uint8)+ mask[:, :2] = 255+ result = registry.get("bitwise").execute(+ {"a": a, "b": b, "mask": mask},+ {"op": "and"},+ seed=0,+ )["image"]+ assert tuple(result[0, 0]) == (255, 255, 255)+ assert tuple(result[0, 3]) == (0, 0, 0)+++def test_absdiff() -> None:+ register_builtin_nodes()+ a = np.full((3, 3, 3), 50, dtype=np.uint8)+ b = np.full((3, 3, 3), 20, dtype=np.uint8)+ result = registry.get("absdiff").execute({"a": a, "b": b}, {}, seed=0)["image"]+ assert tuple(result[0, 0]) == (30, 30, 30)+++def test_add_weighted() -> None:+ register_builtin_nodes()+ a = np.full((2, 2, 3), 100, dtype=np.uint8)+ b = np.full((2, 2, 3), 0, dtype=np.uint8)+ result = registry.get("add_weighted").execute(+ {"a": a, "b": b},+ {"alpha": 0.5, "beta": 0.5, "gamma": 0},+ seed=0,+ )["image"]+ assert tuple(result[0, 0]) == (50, 50, 50)+++def test_arithmetic_add() -> None:+ register_builtin_nodes()+ a = np.full((2, 2, 3), 200, dtype=np.uint8)+ b = np.full((2, 2, 3), 100, dtype=np.uint8)+ result = registry.get("arithmetic").execute(+ {"a": a, "b": b, "mask": None},+ {"op": "add"},+ seed=0,+ )["image"]+ assert tuple(result[0, 0]) == (255, 255, 255) # saturated