【问题标题】:Save dynamic size of Ros messages in arrays将 Ros 消息的动态大小保存在数组中
【发布时间】:2021-04-02 01:47:27
【问题描述】:

我使用 Ros-Yolo 神经网络进行图像识别。我想将通过 Ros-Yolo 神经网络接收到的边界框存储在一个数组中。数组的每个位置应该是下面的结构体。

struct rectangle_box {
  long x_max;
  long y_max;
  long x_min;
  long y_min;
};

由于接收到的边界框的数量会不断变化,我需要一个动态数组。 我现在的问题是哪种程序更明智。

  1. 创建一个上述结构类型的动态数组是否更有用,它会根据每个新收到的消息调整其大小。例如使用 malloc() 函数。
  2. 或者创建一个我定义的足够大的数组来存储足够的边界框是否更有用。例如:std::array bounding_box_in_pixel;

但我需要能够全局访问存储的边界框。

这是我接收边界框数据的回调

void callback_baunding_box (const darknet_ros_msgs::msg::BoundingBoxes::SharedPtr bounding_boxes_msgs)
{


}

这就是我在第二种情况下的解决方法。

struct rectangle_box {
  long x_max;
  long y_max;
  long x_min;
  long y_min;
};

std::array <rectangle_box, 1024> bounding_boxes_in_pixel;

void callback_baunding_box (const darknet_ros_msgs::msg::BoundingBoxes::SharedPtr bounding_boxes_msgs)
{
  for (unsigned long i = 0; i < bounding_boxes_msgs->bounding_boxes.size(); i++)
  {
    bounding_boxes_in_pixel.at(i).x_max = bounding_boxes_msgs->bounding_boxes.at(i).xmax;
    bounding_boxes_in_pixel.at(i).y_max = bounding_boxes_msgs->bounding_boxes.at(i).ymax;
    bounding_boxes_in_pixel.at(i).x_min = bounding_boxes_msgs->bounding_boxes.at(i).xmin;
    bounding_boxes_in_pixel.at(i).y_min = bounding_boxes_msgs->bounding_boxes.at(i).ymin;
  }
}

提前感谢您的帮助

【问题讨论】:

    标签: arrays dynamic eloquent save ros


    【解决方案1】:

    有几种方法可以做到这一点。看看这个非常简单的建议:

    创建一个具有您期望的最大元素大小的向量。这会在后台为您的项目分配一个内存块。

    std::vector<rectangle_box> bounding_boxes_in_pixel(1024);
    

    在每次回调时,调整向量的大小。缩小尺寸不会导致重新分配。这意味着,再次增加大小(不比以前大)也不会导致重新分配 (see this question)。

    void callback_baunding_box (const darknet_ros_msgs::msg::BoundingBoxes::SharedPtr bounding_boxes_msgs)
    {
        //Resize
        bounding_boxes_in_pixel.resize(bounding_boxes_msgs->bounding_boxes.size());
        //Continue to fill
        ...
    }
    

    当然,调整向量的大小也确实需要一些最少的时间(基本上是检查和设置新的大小变量)。但我认为这应该是可以接受的,因为解决方案非常简单易懂。

    【讨论】:

    • 非常感谢您的回答。这对我帮助很大。
    猜你喜欢
    • 2011-08-06
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    相关资源
    最近更新 更多