Tutorial 2: Image node¶
GrayscaleNode reads a compressed camera frame, converts it to grayscale, optionally shrinks it, and publishes the result as a JPEG. After this tutorial you can move images through a node with sensor_msgs/msg/CompressedImage, decode and encode them with OpenCV, expose a numeric setting as a slider through typed configuration, and see the output as a live video stream in the Neuraverse UI without writing any visualization code. The complete node, schema and test live in examples/tutorials/image_node/ and run in CI.
What you build¶
| Port | Direction | rosType |
Purpose |
|---|---|---|---|
start, stop |
trigger in | Start, Stop |
Run once per Start; stop the node. |
image_in |
data in | sensor_msgs/msg/CompressedImage |
JPEG or PNG bytes from a camera or an upstream node. |
image_out |
data out | sensor_msgs/msg/CompressedImage |
The grayscale JPEG. |
start, error |
trigger out | Start, Error |
Chain the next node; route failures to an error handler. |
One setting, scale, is a slider between 0.1 and 1.0. It is declared as a typed rangeValue entry so the UI renders it as a slider, and mirrored in the schema's configuration block as the string "1.0" so the node also works without the typed channel.
Why CompressedImage and not Image¶
Both types are visualized as video and both are accepted by the SDK, but they behave differently on the wire:
sensor_msgs/msg/Image |
sensor_msgs/msg/CompressedImage |
|
|---|---|---|
| Payload | raw pixels, width * height * channels bytes (921,600 bytes for 640x480 BGR) |
JPEG or PNG bytes, typically a few tens of kilobytes for the same frame |
| Over MQTT between edge and cloud | every message is CDR-serialized and base64-encoded inside a JSON envelope, so the raw buffer grows by another third | same envelope, but on a small payload |
| Decoding in Python | reshape msg.data with height, width and encoding |
np.frombuffer plus cv2.imdecode |
| Mock Runner sidebar | cannot render a raw pixel buffer | renders the port inline as an image |
The engine picks the transport per port (ROS 2 or MQTT) when it configures your node; whenever MQTT is chosen, every frame pays the envelope cost above. Keep image ports compressed unless a downstream node needs raw pixels.
Dependencies¶
Decoding and encoding use OpenCV and NumPy. Both are regular dependencies of the SDK (numpy and opencv-python-headless in the SDK's pyproject.toml), so they are already installed in the node base image and in the Mock Runner. Nothing to add for this tutorial.
If your own image node needs more (for example Pillow or a model runtime), add it to the [tool.poetry.dependencies] table of your node project's pyproject.toml; that is what the Dockerfile installs. See Project layout and build.
1. The class¶
class GrayscaleNode(NodeBase):
"""Converts a compressed image to grayscale and re-encodes it as JPEG."""
DEFAULT_SCALE = 1.0
MIN_SCALE = 0.1
MAX_SCALE = 1.0
def __init__(self) -> None:
super().__init__()
# Plain defaults only: real setup happens in on_configure().
self.scale: float = self.DEFAULT_SCALE
__init__ only sets a default. Everything that touches the platform (reading the configuration, opening devices) belongs in on_configure(), which the engine calls with the real values. The class name GrayscaleNode must match executionContext.className in the schema.
2. Describe the scale setting¶
def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
"""Describe the settings the UI shows for this node (typed entries)."""
return {
"scale": NodeConfigEntry(
configValue=NodeConfigValue(
rangeValue=RangeValue(
min=self.MIN_SCALE,
max=self.MAX_SCALE,
value=self.DEFAULT_SCALE,
step=0.1,
)
),
displayLabel="Scale",
description="Resize factor applied to the grayscale image (1.0 keeps the size)",
required=True,
)
}
on_get_configuration() returns a dict of NodeConfigEntry objects, never plain strings. The rangeValue branch carries min, max, value (the default) and step; the UI renders it as a slider and sends the chosen number back to the node through the typed channel. The other branches (stringValue, toggleValue, singleSelectListValue, multiSelectListValue) and the entry fields such as displayLabel, unit and readOnly are listed in Configuration.
3. Read it in on_configure()¶
def on_configure(
self,
config: ScalarMap[str, str],
dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
) -> None:
"""Read the typed ``scale`` value, falling back to the static string map."""
raw_scale = get_config_value("scale", config, dynamic_config)
self.scale = self.DEFAULT_SCALE if raw_scale is None else float(raw_scale)
if not self.MIN_SCALE <= self.scale <= self.MAX_SCALE:
raise NodeConfigurationError(
f"scale must be between {self.MIN_SCALE} and {self.MAX_SCALE}, got {self.scale}"
)
self.log_info(f"GrayscaleNode configured with scale={self.scale}")
Points to note:
- The hook always receives two arguments:
config, the string map from the schema'sconfigurationblock, anddynamic_config, the typed entries edited in the UI (orNone). get_config_value("scale", config, dynamic_config)prefers the typed value and falls back to the static string. It returns a string, orNonewhen neither map has the key, so arangeValueof0.5comes back as"0.5"; convert it withfloat()yourself.- Raising
NodeConfigurationErrorfor an out-of-range value makes the configure step fail and puts the node into the error state, which is what you want for an invalid setting. Do not silently clamp.
4. Process one frame in on_execute()¶
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
"""Convert the latest image on ``image_in`` and publish it on ``image_out``."""
try:
msg = self.get_data("image_in")
if msg is None:
self.log_warning("No image received on 'image_in' yet; nothing to publish")
return
gray = cv2.cvtColor(self._decode(msg), cv2.COLOR_BGR2GRAY)
if self.scale != 1.0:
gray = cv2.resize(
gray, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_AREA
)
self.publish("image_out", self._encode(gray))
except Exception as e:
raise NodeExecutionError(f"Grayscale conversion failed: {e}") from e
self.get_data("image_in")takes only the port key and returns the latestCompressedImageorNone. A node is often triggered before its camera has published, so theNoneguard logs a warning and returns instead of raising.- The whole body is wrapped in
try/exceptand re-raised asNodeExecutionError. The SDK then fires theerroroutput trigger, so a downstream handler can react, and the failure shows up in the node's status. self.publish("image_out", ...)needs a ROS 2 message object. A bare NumPy array is never delivered: the transport rejects it with a log line and nothing arrives downstream;_encode()wraps it.
The SDK runs on_execute() on a single worker thread per node. A Start trigger that arrives while a frame is still being processed is queued and runs afterwards, in order; triggers are never processed in parallel for one node.
5. Decode¶
@staticmethod
def _decode(msg: CompressedImage) -> np.ndarray:
"""Turn the JPEG/PNG bytes of a CompressedImage into a BGR array."""
buffer = np.frombuffer(bytes(msg.data), dtype=np.uint8)
image = cv2.imdecode(buffer, cv2.IMREAD_COLOR)
if image is None:
raise ValueError(f"Could not decode image with format {msg.format!r}")
return image
msg.data is the byte sequence of the compressed file exactly as the publisher produced it. np.frombuffer views those bytes as a uint8 array, cv2.imdecode turns that into a BGR array, and a None result means the bytes were not a decodable image. The format field of the message ("jpeg", "png") is informational; OpenCV detects the format from the bytes.
6. Encode¶
@staticmethod
def _encode(image: np.ndarray) -> CompressedImage:
"""Encode an array as JPEG and wrap it in a CompressedImage message."""
ok, encoded = cv2.imencode(".jpg", image)
if not ok:
raise ValueError("Could not encode image as JPEG")
return CompressedImage(format="jpeg", data=encoded.tobytes())
cv2.imencode(".jpg", image) returns a success flag and a NumPy array of bytes. tobytes() and the format="jpeg" field give you a CompressedImage that any other node, the Neuraverse UI and the Mock Runner can display.
7. The schema¶
Save this next to the module as image_node_schema.json:
{
"id": "Examples",
"name": "GrayscaleNode",
"type": 1,
"description": "Converts a compressed image to grayscale and re-encodes it as JPEG",
"tags": ["example", "tutorial", "image"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 },
"image_in": {
"rosType": "sensor_msgs/msg/CompressedImage",
"edgeType": 1
}
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 },
"image_out": {
"rosType": "sensor_msgs/msg/CompressedImage",
"edgeType": 1
}
},
"errorOutputs": {},
"dataFlowEntry": {},
"triggerFlowEntry": {},
"executionContext": {
"type": "EXECUTION_TARGET_TYPE_GRPC",
"target": "",
"className": "GrayscaleNode"
},
"configuration": { "scale": "1.0" }
}
Data ports carry the message type verbatim as pkg/msg/Type in rosType; trigger ports carry the trigger type name. There is no stop output: the SDK fires every declared Stop output after each successful execution, which would stop the next node on every frame. The configuration block holds the static default for scale as a string. The full field list is in the Schema file reference.
8. Register the node¶
Add the class to the list in run_nodes.py of your node project:
from neuraverse_sdk.node_manager_service import run, set_node_classes
from image_node.image_node import GrayscaleNode
set_node_classes([GrayscaleNode])
run()
Run it in the Mock Runner¶
The Mock Runner can execute this node on your laptop, with two things to know about images:
- The Override control cannot inject a
CompressedImageby hand (the row shows a file picker, but the value is rejected silently). Feedimage_infrom an upstream node instead. The node-template shipsFloatPublisherNode, which publishes a random 640x480 JPEG on itsimage_outputport; connect that port toimage_in. - Ports typed
sensor_msgs/msg/CompressedImageare rendered inline as an image in the Inputs and Outputs tabs, so you can see the grayscale result without leaving the browser.
Steps:
- Start the Mock Runner with your sources mounted. Either copy the
image_node/folder into your node project'ssrc/directory next to the template nodes, or pointSRC_DIRPATHat a directory that contains it and the publisher (see the Mock Runner documentation, or Testing). - Drag
FloatPublisherNodeandGrayscaleNodeonto the canvas and connectimage_outputtoimage_in. - Click Init, then Configure on both nodes. Change
scalein the configuration panel if you want a smaller output. - Execute the publisher, then Execute
GrayscaleNode. The Outputs tab ofGrayscaleNodeshows the grayscale JPEG.
Executing GrayscaleNode again without executing the publisher processes the same frame again: get_data() returns the last value on the port until a new message arrives. That is the real adapter behaviour, not a mock artefact.
Visualization for free¶
On a real engine you get a live video stream of image_out in the Neuraverse UI without any extra code. The SDK forwards every message you pass to publish() on a visualizable output port to the viewer while somebody has the node open, and it keeps the last published message per port so a viewer who opens the panel late sees the current frame immediately. Which types are rendered as video, audio or JSON, and the few types that are excluded, are listed in Data visualization. The Mock Runner does not stream visualizations; its inline previews are its own rendering.
Performance notes¶
| Concern | What to do |
|---|---|
Every Start trigger runs on_execute() once, on one worker thread |
Keep one execution short (decode, process, encode). If triggers arrive faster than you process them they queue up and the node falls behind; drop work inside the node or lower the upstream rate. |
get_data() returns the latched last message |
If you must process each frame exactly once, remember the last object you handled (or a header stamp) and skip duplicates. |
| Until the first message arrives on a connected port, every read waits up to 1 s | The wait ends for good once one message has arrived; after that reads return at once. Do not read several possibly empty ports in a hot loop. |
| Large frames | Resize before encoding (this node uses cv2.INTER_AREA for downscaling) and keep ports compressed. Raw Image messages of a full HD camera are 6 MB each before base64. |
| Publishing arrays or bytes directly | Never. Wrap the result in a message object; a bare array is dropped. |
The test that CI runs¶
examples/tutorials/image_node/test_image_node.py drives the node without ROS or a platform. It installs the shared message stubs, replaces the transport with FakeDataFlow, puts a tiny solid-blue JPEG on image_in and checks that image_out receives a single-channel JPEG of the expected size. Further cases cover the typed rangeValue from dynamicConfiguration, the static fallback, an out-of-range scale raising NodeConfigurationError, no input publishing nothing, and undecodable bytes raising NodeExecutionError. Run it with:
PYTHONPATH="$(pwd):$(pwd)/src" poetry run pytest examples/tutorials/image_node -q
Testing explains the stubs and the fake data flow, and how to reuse the same pattern for your own nodes.
Next steps¶
- Tutorial 3: Device node (smart home) adds state, a toggle and a string setting, health reporting and simulation mode.
- Configuration for all typed value branches and how the two channels interact.
- Dataflow for the exact
get_data()andpublish()semantics used above.