image_publisher.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # simple script to publish a image from a file.
3 import rospy
4 import rospkg
5 import time
6 import cv2
7 import sensor_msgs.msg
8 
9 def callback(self):
10  """ Convert a image to a ROS compatible message
11  (sensor_msgs.Image).
12  """
13  global publisher, imagePath
14 
15  img = cv2.imread(imagePath, cv2.IMREAD_UNCHANGED)
16 
17 # print img.shape
18 # print img.size
19 # print img.dtype.itemsize
20 
21  rosimage = sensor_msgs.msg.Image()
22  if img.dtype.itemsize == 2:
23  if len(img.shape) == 3:
24  if img.shape[2] == 3:
25  rosimage.encoding = 'bgr16'
26  if img.shape[2] == 4:
27  rosimage.encoding = 'bgra16'
28  else:
29  rosimage.encoding = 'mono16'
30  if img.dtype.itemsize == 1:
31  if len(img.shape) == 3:
32  if img.shape[2] == 3:
33  rosimage.encoding = 'bgr8'
34  if img.shape[2] == 4:
35  rosimage.encoding = 'bgra8'
36  else:
37  rosimage.encoding = 'mono8'
38 # print "Encoding: ", rosimage.encoding
39 
40  rosimage.width = img.shape[1]
41  rosimage.height = img.shape[0]
42  rosimage.step = img.strides[0]
43  rosimage.data = img.tostring()
44  rosimage.header.stamp = rospy.Time.now()
45  rosimage.header.frame_id = 'map'
46 
47  publisher.publish(rosimage)
48 
49 
50 #Main function initializes node and subscribers and starts the ROS loop
52  global publisher, imagePath
53  rospack = rospkg.RosPack()
54  rospy.init_node('image_publisher')
55  imagePath = rospy.get_param('~image_path')
56  topicName = rospy.get_param('~topic')
57  publisher = rospy.Publisher(topicName, sensor_msgs.msg.Image, queue_size=10)
58  rospy.Timer(rospy.Duration(2), callback)
59  rospy.spin()
60 
61 if __name__ == '__main__':
62  try:
63  main_program()
64  except rospy.ROSInterruptException: pass
def callback(self)


grid_map_demos
Author(s): Péter Fankhauser
autogenerated on Tue Jun 1 2021 02:13:55