extract_image_channel.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 
7 import re
8 import sys
9 
10 import numpy as np
11 
12 import cv_bridge
13 import dynamic_reconfigure.server
14 from jsk_perception.cfg import ExtractImageChannelConfig
15 from jsk_topic_tools import ConnectionBasedTransport
16 from jsk_topic_tools.log_utils import logwarn_throttle
17 import rospy
18 from sensor_msgs.msg import Image
19 
20 
21 # See https://github.com/ros-perception/vision_opencv/pull/141
22 # for PR to upstream
23 class CvBridgeArbitraryChannels(cv_bridge.CvBridge):
24 
25  def encoding_to_dtype_with_channels(self, encoding):
26  try:
27  return self.cvtype2_to_dtype_with_channels(self.encoding_to_cvtype2(encoding))
28  except cv_bridge.CvBridgeError as e:
29  try:
30  vals = re.split('(.+)C(.+)', encoding)
31  dtype, n_channels = self.numpy_type_to_cvtype[vals[1]], int(vals[2])
32  return dtype, n_channels
33  except Exception as e:
34  raise cv_bridge.CvBridgeError(e)
35 
36 
37 class ExtractImageChannel(ConnectionBasedTransport):
38 
39  def __init__(self):
40  super(self.__class__, self).__init__()
41  dynamic_reconfigure.server.Server(
42  ExtractImageChannelConfig, self._config_callback)
43  self.pub = self.advertise('~output', Image, queue_size=1)
44 
45  def _config_callback(self, config, level):
46  self.channel = config.channel
47  return config
48 
49  def subscribe(self):
50  self.sub = rospy.Subscriber('~input', Image, self._callback)
51 
52  def unsubscribe(self):
53  self.sub.unregister()
54 
55  def _callback(self, imgmsg):
56  if self.channel < 0:
57  return
58  bridge = CvBridgeArbitraryChannels()
59  img = bridge.imgmsg_to_cv2(imgmsg)
60  if img.ndim == 2:
61  img = img[:, :, np.newaxis]
62  if not (self.channel < img.shape[2]):
63  logwarn_throttle(10,
64  'Invalid channel {} is specified for image with {} channels'
65  .format(self.channel, img.shape[2]))
66  return
67  out_img = np.zeros(img.shape[:2], dtype=img.dtype)
68  out_img = img[:, :, self.channel]
69  out_imgmsg = bridge.cv2_to_imgmsg(out_img)
70  out_imgmsg.header = imgmsg.header
71  self.pub.publish(out_imgmsg)
72 
73 
74 if __name__ == '__main__':
75  rospy.init_node('extract_image_channel')
77  rospy.spin()


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