split_fore_background.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 import numpy as np
5 
6 import cv_bridge
7 from jsk_recognition_utils.depth import split_fore_background
8 from jsk_topic_tools import ConnectionBasedTransport
9 import rospy
10 from sensor_msgs.msg import Image
11 
12 
13 class SplitForeBackground(ConnectionBasedTransport):
14 
15  def __init__(self):
16  super(SplitForeBackground, self).__init__()
17  self.fg_mask_pub_ = self.advertise(
18  '~output/fg_mask', Image, queue_size=10)
19  self.bg_mask_pub_ = self.advertise(
20  '~output/bg_mask', Image, queue_size=10)
21 
22  def subscribe(self):
23  self.sub = rospy.Subscriber('~input', Image, self._apply)
24 
25  def unsubscribe(self):
26  self.sub.unregister()
27 
28  def _apply(self, depth_msg):
29  # validation
30  supported_encodings = {'16UC1', '32FC1'}
31  if depth_msg.encoding not in supported_encodings:
32  rospy.logwarn('Unsupported depth image encoding: {0}'
33  .format(depth_msg.encoding))
34  # split fg/bg and get each mask
35  bridge = cv_bridge.CvBridge()
36  depth = bridge.imgmsg_to_cv2(depth_msg)
37  nan_mask = None
38  if depth_msg.encoding == '32FC1':
39  # convert float to int (handle 32FC1 as 16UC1)
40  nan_mask = np.isnan(depth)
41  depth[nan_mask] = 0
42  depth *= 255
43  depth = depth.astype(np.uint8)
44  fg_mask, bg_mask = split_fore_background(depth)
45  if nan_mask is not None:
46  fg_mask[nan_mask] = 0
47  bg_mask[nan_mask] = 0
48  # fg_mask
49  fg_mask = (fg_mask * 255).astype(np.uint8)
50  fg_mask_msg = bridge.cv2_to_imgmsg(fg_mask, encoding='mono8')
51  fg_mask_msg.header = depth_msg.header
52  self.fg_mask_pub_.publish(fg_mask_msg)
53  # bg_mask
54  bg_mask = (bg_mask * 255).astype(np.uint8)
55  bg_mask_msg = bridge.cv2_to_imgmsg(bg_mask, encoding='mono8')
56  bg_mask_msg.header = depth_msg.header
57  self.bg_mask_pub_.publish(bg_mask_msg)
58 
59 
60 if __name__ == '__main__':
61  rospy.init_node('split_fore_background')
62  split_fbg = SplitForeBackground()
63  rospy.spin()


jsk_perception
Author(s): Manabu Saito, Ryohei Ueda
autogenerated on Mon May 3 2021 03:03:27