segment_objects_nodelet.cpp
Go to the documentation of this file.
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2014, Kei Okada.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
17 * * Neither the name of the Kei Okada nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 *********************************************************************/
34 
35 // https://github.com/Itseez/opencv/blob/2.4/samples/cpp/segment_objects.cpp
40 #include <ros/ros.h>
41 #include "opencv_apps/nodelet.h"
43 #include <cv_bridge/cv_bridge.h>
45 
46 #include <opencv2/highgui/highgui.hpp>
47 #include <opencv2/imgproc/imgproc.hpp>
48 #include <opencv2/video/background_segm.hpp>
49 
50 #include <dynamic_reconfigure/server.h>
51 #include "opencv_apps/SegmentObjectsConfig.h"
52 #include "std_srvs/Empty.h"
53 #include "std_msgs/Float64.h"
54 #include "opencv_apps/Contour.h"
55 #include "opencv_apps/ContourArray.h"
56 #include "opencv_apps/ContourArrayStamped.h"
57 
58 namespace opencv_apps
59 {
61 {
67 
69 
70  typedef opencv_apps::SegmentObjectsConfig Config;
71  typedef dynamic_reconfigure::Server<Config> ReconfigureServer;
72  Config config_;
74 
78 
79  std::string window_name_;
80  static bool need_config_update_;
81 
82 #ifndef CV_VERSION_EPOCH
83  cv::Ptr<cv::BackgroundSubtractorMOG2> bgsubtractor;
84 #else
85  cv::BackgroundSubtractorMOG bgsubtractor;
86 #endif
88 
89  void reconfigureCallback(Config& new_config, uint32_t level)
90  {
91  config_ = new_config;
92  }
93 
94  const std::string& frameWithDefault(const std::string& frame, const std::string& image_frame)
95  {
96  if (frame.empty())
97  return image_frame;
98  return frame;
99  }
100 
101  void imageCallbackWithInfo(const sensor_msgs::ImageConstPtr& msg, const sensor_msgs::CameraInfoConstPtr& cam_info)
102  {
103  doWork(msg, cam_info->header.frame_id);
104  }
105 
106  void imageCallback(const sensor_msgs::ImageConstPtr& msg)
107  {
108  doWork(msg, msg->header.frame_id);
109  }
110 
111  static void trackbarCallback(int /*unused*/, void* /*unused*/)
112  {
113  need_config_update_ = true;
114  }
115 
116  void doWork(const sensor_msgs::ImageConstPtr& msg, const std::string& input_frame_from_msg)
117  {
118  // Work on the image.
119  try
120  {
121  // Convert the image into something opencv can handle.
122  cv::Mat frame = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::BGR8)->image;
123 
124  // Messages
125  opencv_apps::ContourArrayStamped contours_msg;
126  contours_msg.header = msg->header;
127 
128  // Do the work
129  cv::Mat bgmask, out_frame;
130 
131  if (debug_view_)
132  {
134  cv::namedWindow(window_name_, cv::WINDOW_AUTOSIZE);
135  if (need_config_update_)
136  {
137  reconfigure_server_->updateConfig(config_);
138  need_config_update_ = false;
139  }
140  }
141 
142 #ifndef CV_VERSION_EPOCH
143  bgsubtractor->apply(frame, bgmask, update_bg_model ? -1 : 0);
144 #else
145  bgsubtractor(frame, bgmask, update_bg_model ? -1 : 0);
146 #endif
147  // refineSegments(tmp_frame, bgmask, out_frame);
148  int niters = 3;
149 
150  std::vector<std::vector<cv::Point> > contours;
151  std::vector<cv::Vec4i> hierarchy;
152 
153  cv::Mat temp;
154 
155  cv::dilate(bgmask, temp, cv::Mat(), cv::Point(-1, -1), niters);
156  cv::erode(temp, temp, cv::Mat(), cv::Point(-1, -1), niters * 2);
157  cv::dilate(temp, temp, cv::Mat(), cv::Point(-1, -1), niters);
158 
159  cv::findContours(temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
160 
161  out_frame = cv::Mat::zeros(frame.size(), CV_8UC3);
162 
163  if (contours.empty())
164  return;
165 
166  // iterate through all the top-level contours,
167  // draw each connected component with its own random color
168  int idx = 0, largest_comp = 0;
169  double max_area = 0;
170 
171  for (; idx >= 0; idx = hierarchy[idx][0])
172  {
173  const std::vector<cv::Point>& c = contours[idx];
174  double area = fabs(cv::contourArea(cv::Mat(c)));
175  if (area > max_area)
176  {
177  max_area = area;
178  largest_comp = idx;
179  }
180  }
181  cv::Scalar color(0, 0, 255);
182  cv::drawContours(out_frame, contours, largest_comp, color, CV_FILLED, 8, hierarchy);
183 
184  std_msgs::Float64 area_msg;
185  area_msg.data = max_area;
186  for (const std::vector<cv::Point>& contour : contours)
187  {
188  opencv_apps::Contour contour_msg;
189  for (const cv::Point& j : contour)
190  {
191  opencv_apps::Point2D point_msg;
192  point_msg.x = j.x;
193  point_msg.y = j.y;
194  contour_msg.points.push_back(point_msg);
195  }
196  contours_msg.contours.push_back(contour_msg);
197  }
198 
199  //-- Show what you got
200  if (debug_view_)
201  {
202  cv::imshow(window_name_, out_frame);
203  int keycode = cv::waitKey(1);
204  // if( keycode == 27 )
205  // break;
206  if (keycode == ' ')
207  {
208  update_bg_model = !update_bg_model;
209  NODELET_INFO("Learn background is in state = %d", update_bg_model);
210  }
211  }
212 
213  // Publish the image.
214  sensor_msgs::Image::Ptr out_img =
216  img_pub_.publish(out_img);
217  msg_pub_.publish(contours_msg);
218  area_pub_.publish(area_msg);
219  }
220  catch (cv::Exception& e)
221  {
222  NODELET_ERROR("Image processing error: %s %s %s %i", e.err.c_str(), e.func.c_str(), e.file.c_str(), e.line);
223  }
224 
225  prev_stamp_ = msg->header.stamp;
226  }
227 
228  bool updateBgModelCb(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response)
229  {
230  update_bg_model = !update_bg_model;
231  NODELET_INFO("Learn background is in state = %d", update_bg_model);
232  return true;
233  }
234 
235  void subscribe() // NOLINT(modernize-use-override)
236  {
237  NODELET_DEBUG("Subscribing to image topic.");
238  if (config_.use_camera_info)
239  cam_sub_ = it_->subscribeCamera("image", queue_size_, &SegmentObjectsNodelet::imageCallbackWithInfo, this);
240  else
241  img_sub_ = it_->subscribe("image", queue_size_, &SegmentObjectsNodelet::imageCallback, this);
242  }
243 
244  void unsubscribe() // NOLINT(modernize-use-override)
245  {
246  NODELET_DEBUG("Unsubscribing from image topic.");
247  img_sub_.shutdown();
248  cam_sub_.shutdown();
249  }
250 
251 public:
252  virtual void onInit() // NOLINT(modernize-use-override)
253  {
254  Nodelet::onInit();
256 
257  pnh_->param("queue_size", queue_size_, 3);
258  pnh_->param("debug_view", debug_view_, false);
259  if (debug_view_)
260  {
261  always_subscribe_ = true;
262  }
263  prev_stamp_ = ros::Time(0, 0);
264 
265  window_name_ = "segmented";
266  update_bg_model = true;
267 
268 #ifndef CV_VERSION_EPOCH
269  bgsubtractor = cv::createBackgroundSubtractorMOG2();
270 #else
271  bgsubtractor.set("noiseSigma", 10);
272 #endif
273 
274  reconfigure_server_ = boost::make_shared<dynamic_reconfigure::Server<Config> >(*pnh_);
275  dynamic_reconfigure::Server<Config>::CallbackType f =
276  boost::bind(&SegmentObjectsNodelet::reconfigureCallback, this, _1, _2);
277  reconfigure_server_->setCallback(f);
278 
279  img_pub_ = advertiseImage(*pnh_, "image", 1);
280  msg_pub_ = advertise<opencv_apps::ContourArrayStamped>(*pnh_, "contours", 1);
281  area_pub_ = advertise<std_msgs::Float64>(*pnh_, "area", 1);
282  update_bg_model_service_ = pnh_->advertiseService("update_bg_model", &SegmentObjectsNodelet::updateBgModelCb, this);
283 
285  }
286 };
288 } // namespace opencv_apps
289 
291 {
293 {
294 public:
295  virtual void onInit() // NOLINT(modernize-use-override)
296  {
297  ROS_WARN("DeprecationWarning: Nodelet segment_objects/segment_objects is deprecated, "
298  "and renamed to opencv_apps/segment_objects.");
300  }
301 };
302 } // namespace segment_objects
303 
CvImageConstPtr toCvShare(const sensor_msgs::ImageConstPtr &source, const std::string &encoding=std::string())
void imageCallback(const sensor_msgs::ImageConstPtr &msg)
#define NODELET_ERROR(...)
void publish(const boost::shared_ptr< M > &message) const
f
Nodelet to automatically subscribe/unsubscribe topics according to subscription of advertised topics...
Definition: nodelet.h:70
Demo code to calculate moments.
Definition: nodelet.h:48
const std::string & frameWithDefault(const std::string &frame, const std::string &image_frame)
image_transport::CameraSubscriber cam_sub_
void unsubscribe()
This method is called when publisher is unsubscribed by other nodes. Shut down subscribers in this me...
void imageCallbackWithInfo(const sensor_msgs::ImageConstPtr &msg, const sensor_msgs::CameraInfoConstPtr &cam_info)
boost::shared_ptr< ros::NodeHandle > pnh_
Shared pointer to private nodehandle.
Definition: nodelet.h:250
#define ROS_WARN(...)
void subscribe()
This method is called when publisher is subscribed by other nodes. Set up subscribers in this method...
bool always_subscribe_
A flag to disable watching mechanism and always subscribe input topics. It can be specified via ~alwa...
Definition: nodelet.h:273
opencv_apps::SegmentObjectsConfig Config
virtual void onInitPostProcess()
Post processing of initialization of nodelet. You need to call this method in order to use always_sub...
Definition: nodelet.cpp:57
virtual void onInit()
Initialize nodehandles nh_ and pnh_. Subclass should call this method in its onInit method...
Definition: nodelet.cpp:40
void publish(const sensor_msgs::Image &message) const
void doWork(const sensor_msgs::ImageConstPtr &msg, const std::string &input_frame_from_msg)
boost::shared_ptr< ros::NodeHandle > nh_
Shared pointer to nodehandle.
Definition: nodelet.h:245
dynamic_reconfigure::Server< Config > ReconfigureServer
image_transport::Publisher advertiseImage(ros::NodeHandle &nh, const std::string &topic, int queue_size)
Advertise an image topic and watch the publisher. Publishers which are created by this method...
Definition: nodelet.h:180
#define NODELET_INFO(...)
PLUGINLIB_EXPORT_CLASS(opencv_apps::SegmentObjectsNodelet, nodelet::Nodelet)
virtual void onInit()
Initialize nodehandles nh_ and pnh_. Subclass should call this method in its onInit method...
bool updateBgModelCb(std_srvs::Empty::Request &request, std_srvs::Empty::Response &response)
boost::shared_ptr< image_transport::ImageTransport > it_
boost::shared_ptr< ReconfigureServer > reconfigure_server_
virtual void onInit()
Initialize nodehandles nh_ and pnh_. Subclass should call this method in its onInit method...
#define NODELET_DEBUG(...)
sensor_msgs::ImagePtr toImageMsg() const
cv::Ptr< cv::BackgroundSubtractorMOG2 > bgsubtractor
void reconfigureCallback(Config &new_config, uint32_t level)


opencv_apps
Author(s): Kei Okada
autogenerated on Wed Apr 24 2019 03:00:17