0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ROS2で多次元配列を送受信する - ndarray_msg -

Posted at

背景

深層学習では、深層モデルから出力される純粋な特徴量はテンソル(多次元配列)として表現されます。

ROS2には画像やポイントクラウドなど、豊富なメッセージ型が用意されていますが、深層学習のような、純粋な多次元配列だけを送受信したいケースもあります。

ということで、今回はNumPyの多次元配列(ndarray)を簡単にROS2ノード間で送受信できるパッケージ ndarray_msg を作成しました。

ROS2のDistroは HumbleJazzyで検証しています。

GitHubリポジトリ

パッケージのソースコードは以下のリポジトリで公開しています:

使い方

インストール方法

  1. まず、ROS2のワークスペースにパッケージをクローンします:
cd ~/ros2_ws/src
git clone https://github.com/Geson-anko/ndarray_msg.git
  1. パッケージをビルドします:
cd ~/ros2_ws
colcon build --packages-select ndarray_msg
source install/setup.sh
  1. Python用のユーティリティパッケージをインストールします:
cd ~/ros2_ws/src/ndarray_msg
pip install .  # uv などを使っている場合は uv add <path/to/ndarray_msg>

基本的な使用例

NumPy配列をROS2メッセージに変換し、別のノードで受信して元の配列に戻す基本的な例:

import numpy as np
from ndarray_msg_utils import to_ros_msg, from_ros_msg
from rclpy.clock import ROSClock

# NumPy配列をROS2メッセージに変換
array = np.array([[1, 2], [3, 4]], dtype=np.float32)
msg = to_ros_msg(array)

# ヘッダ情報付きでメッセージを作成
msg = to_ros_msg(
    array,
    timestamp=ROSClock().now(),
    frame_id="camera_frame"
)

# メッセージからNumPy配列に戻す
restored = from_ros_msg(msg)

メッセージの詳細について

# NDArray message type for pure numerical data
std_msgs/Header header # header information
string dtype          # numpy dtype name (e.g., 'float32', 'float64', 'int64')
uint32[] shape        # ndarray dimensions
uint32 data_size      # total number of elements
uint8[] data          # serialized ndarray data

各フィールドの役割:

  • header: 標準的なROS2ヘッダ(タイムスタンプとフレームID)
  • dtype: NumPy配列のデータ型名(例:'float32', 'int64')
  • shape: 配列の各次元のサイズ
  • data_size: 配列の全要素数
  • data: バイト列にシリアライズされた配列データ

最後に

とりあえずザッと作った簡易なパッケージですので、プロジェクトにそのままコードを移植して使用しても良いと思います。

何か皆さんのお役に立てば幸いです〜

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?