smach_image_publisher.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import copy
4 import cv2
5 import cv_bridge
6 import imp
7 import numpy as np
8 import os
9 import rospy
10 import subprocess
11 import sys
12 import time
13 
14 from sensor_msgs.msg import CompressedImage
15 from sensor_msgs.msg import Image
16 
17 try:
18  # this import system (or ros-released) xdot
19  # import xdot
20  # need to import currnt package, but not to load this file
21  # http://stackoverflow.com/questions/6031584/importing-from-builtin-library-when-module-with-same-name-exists
22  def import_non_local(name, custom_name=None):
23  custom_name = custom_name or name
24 
25  path = filter(lambda x: x != os.path.dirname(os.path.abspath(__file__)), sys.path)
26  f, pathname, desc = imp.find_module(name, path)
27 
28  module = imp.load_module(custom_name, f, pathname, desc)
29  if f:
30  f.close()
31 
32  return module
33 
34  smach_viewer = import_non_local('smach_viewer')
35  from smach_viewer.smach_viewer_base import SmachViewerBase
36 except Exception:
37  # Guard against self import
38  this_dir = os.path.dirname(__file__)
39  # Use os.getcwd() to aovid weird symbolic link problems
40  cur_dir = os.getcwd()
41  os.chdir(this_dir)
42  this_dir_cwd = os.getcwd()
43  os.chdir(cur_dir)
44  # Remove this dir from path
45  sys.path = [a for a in sys.path if a not in [this_dir, this_dir_cwd]]
46  # Ignore path ending with smach_viewer/lib/smach_viewer
47  sys.path = [a for a in sys.path if not a.endswith('smach_viewer/lib/smach_viewer')]
48  #
49  from smach_viewer.smach_viewer_base import SmachViewerBase
50 
51 
52 if sys.version_info[0] >= 3:
53  unicode = str
54 
55 
57 
58  def __init__(self):
59  super(SmachImagePublisher, self).__init__()
60  self.bridge = cv_bridge.CvBridge()
61  duration = rospy.get_param('~duration', 0.1)
62  self.image_width = rospy.get_param('~image_width', 1000)
63  self.image_height = rospy.get_param('~image_height', 1500)
64  self.image_dpi = rospy.get_param('~image_dpi', 500)
65 
66  self.filepath = '/tmp/smach_image_publisher_{}.png'.format(
67  os.getpid())
68  self._timer = rospy.Timer(
69  rospy.Duration(duration), self._timer_cb)
70  self._pub = rospy.Publisher('~image', Image, queue_size=1)
71  self._pub_compressed = rospy.Publisher(
72  '~image/compressed', CompressedImage, queue_size=1)
73 
74  def _timer_cb(self, event):
75  with self._update_cond:
76  dotcode = copy.copy(self.dotstr)
77  if sys.version_info[0] < 3 and isinstance(dotcode, unicode):
78  dotcode = dotcode.encode('utf8')
79 
80  w_scale = self.image_width // self.image_dpi
81  h_scale = self.image_height // self.image_dpi
82  p = subprocess.Popen(
83  [
84  'dot',
85  '-Tpng',
86  '-Gsize={},{}\\!'.format(w_scale, h_scale),
87  '-Gdpi={}'.format(self.image_dpi),
88  '-o{}'.format(self.filepath)
89  ],
90  stdin=subprocess.PIPE,
91  stdout=subprocess.PIPE,
92  stderr=subprocess.PIPE,
93  shell=False,
94  universal_newlines=True
95  )
96  _, error = p.communicate(dotcode)
97  if p.returncode != 0:
98  rospy.logerr("ERROR PARSING DOT CODE {}".format(error))
99  return False
100 
101  if not os.path.exists(self.filepath):
102  return
103  if os.path.getsize(self.filepath) == 0:
104  return
105 
106  img = cv2.imread(self.filepath)
107  H, W, _ = img.shape
108  if self.image_width > W or self.image_height > H:
109  top_pad = (self.image_height - H) // 2
110  bottom_pad = self.image_height - H - top_pad
111  left_pad = (self.image_width - W) // 2
112  right_pad = self.image_width - W - left_pad
113  img = cv2.copyMakeBorder(
114  img, top_pad, bottom_pad, left_pad, right_pad,
115  cv2.BORDER_CONSTANT, value=(255, 255, 255))
116  img_msg = self.bridge.cv2_to_imgmsg(img, encoding='bgr8')
117  img_msg.header.stamp = rospy.Time.now()
118  self._pub.publish(img_msg)
119  compressed_img_msg = CompressedImage()
120  compressed_img_msg.header = img_msg.header
121  compressed_img_msg.format = img_msg.encoding
122  compressed_img_msg.format += '; jpeg compressed bgr8'
123  compressed_img_msg.data = np.array(
124  cv2.imencode('.jpg', img)[1]).tostring()
125  self._pub_compressed.publish(compressed_img_msg)
126 
127  def remove_file(self):
128  # wait and loop until file is removed
129  while os.path.exists(self.filepath):
130  rospy.logwarn(
131  'Removing file: {}'.format(self.filepath))
132  os.remove(self.filepath)
133  time.sleep(0.1)
134 
135 
136 if __name__ == '__main__':
137  rospy.init_node('smach_image_publisher')
139 
141  rospy.logwarn('Killing threads...')
142  app.kill()
143  app.remove_file()
144 
145  rospy.on_shutdown(signal_handler)
146  rospy.spin()
smach_viewer.smach_viewer_base.SmachViewerBase.dotstr
dotstr
Definition: smach_viewer_base.py:311
smach_image_publisher.SmachImagePublisher.filepath
filepath
Definition: smach_image_publisher.py:66
smach_image_publisher.import_non_local
def import_non_local(name, custom_name=None)
Definition: smach_image_publisher.py:22
smach_image_publisher.SmachImagePublisher.bridge
bridge
Definition: smach_image_publisher.py:60
smach_viewer.smach_viewer_base.SmachViewerBase._update_cond
_update_cond
Definition: smach_viewer_base.py:309
smach_image_publisher.SmachImagePublisher.image_dpi
image_dpi
Definition: smach_image_publisher.py:64
smach_image_publisher.SmachImagePublisher.remove_file
def remove_file(self)
Definition: smach_image_publisher.py:127
smach_image_publisher.SmachImagePublisher.image_height
image_height
Definition: smach_image_publisher.py:63
smach_image_publisher.SmachImagePublisher.image_width
image_width
Definition: smach_image_publisher.py:62
smach_image_publisher.signal_handler
def signal_handler()
Definition: smach_image_publisher.py:140
smach_image_publisher.SmachImagePublisher._timer_cb
def _timer_cb(self, event)
Definition: smach_image_publisher.py:74
smach_image_publisher.SmachImagePublisher
Definition: smach_image_publisher.py:56
smach_image_publisher.SmachImagePublisher._pub_compressed
_pub_compressed
Definition: smach_image_publisher.py:71
smach_image_publisher.SmachImagePublisher.__init__
def __init__(self)
Definition: smach_image_publisher.py:58
smach_image_publisher.SmachImagePublisher._timer
_timer
Definition: smach_image_publisher.py:68
smach_viewer.smach_viewer_base
Definition: smach_viewer_base.py:1
smach_viewer.smach_viewer_base.SmachViewerBase
Definition: smach_viewer_base.py:301
smach_image_publisher.SmachImagePublisher._pub
_pub
Definition: smach_image_publisher.py:70


smach_viewer
Author(s): Jonathan Bohren
autogenerated on Thu Feb 20 2025 03:09:09