Go to the documentation of this file.00001
00002
00003
00004 import cv2
00005 import numpy as np
00006
00007 import cv_bridge
00008 import jsk_topic_tools
00009 import rospy
00010 from sensor_msgs.msg import Image
00011
00012
00013 def cv_centerize(src, dst_shape):
00014 """Centerize image for specified image size
00015
00016 @param src: image to centerize
00017 @param dst_shape: image shape (height, width) or (height, width, channel)
00018 """
00019 if src.shape[:2] == dst_shape[:2]:
00020 return src
00021 centerized = np.zeros(dst_shape, dtype=src.dtype)
00022 pad_vertical, pad_horizontal = 0, 0
00023 h, w = src.shape[:2]
00024 dst_h, dst_w = dst_shape[:2]
00025 if h < dst_h:
00026 pad_vertical = (dst_h - h) // 2
00027 if w < dst_w:
00028 pad_horizontal = (dst_w - w) // 2
00029 centerized[pad_vertical:pad_vertical+h,
00030 pad_horizontal:pad_horizontal+w] = src
00031 return centerized
00032
00033
00034 class XdisplayImageTopic(object):
00035
00036 def __init__(self, from_topic):
00037 self.pub = rospy.Publisher('/robot/xdisplay', Image, queue_size=10)
00038 self.sub = rospy.Subscriber(from_topic, Image, self.cb)
00039 self.do_resize = rospy.get_param('~resize', True)
00040 self.do_centerize = rospy.get_param('~centerize', True)
00041 if not self.do_resize and self.do_centerize:
00042 jsk_topic_tools.jsk_logerr(
00043 "If '~centerize' is True, '~resize' must be True also."
00044 " Stopping centerizing.")
00045 self.do_centerize = False
00046
00047 def cb(self, msg):
00048 if not self.do_resize:
00049 self.pub.publish(msg)
00050 return
00051
00052
00053 MAX_WIDTH = 1024
00054 MAX_HEIGHT = 600
00055
00056
00057 br = cv_bridge.CvBridge()
00058 img = br.imgmsg_to_cv2(msg, desired_encoding='bgr8')
00059 h, w = img.shape[:2]
00060 if h > MAX_HEIGHT:
00061 scale = 1. * MAX_HEIGHT / h
00062 h = MAX_HEIGHT
00063 w = int(scale * w)
00064 if w > MAX_WIDTH:
00065 scale = 1. * MAX_WIDTH / w
00066 w = MAX_WIDTH
00067 h = int(scale * h)
00068 img = cv2.resize(img, (w, h))
00069
00070
00071 centerized_shape = (MAX_HEIGHT, MAX_WIDTH, 3)
00072 if self.do_centerize:
00073 img = cv_centerize(img, centerized_shape)
00074
00075 imgmsg = br.cv2_to_imgmsg(img)
00076 imgmsg.header = msg.header
00077 self.pub.publish(imgmsg)
00078
00079
00080 if __name__ == '__main__':
00081 rospy.init_node('xdisplay_image_topic')
00082
00083 import argparse
00084 parser = argparse.ArgumentParser()
00085 parser.add_argument('from_topic', help='Image topic to relay to xdisplay')
00086 args = parser.parse_args(rospy.myargv()[1:])
00087 from_topic = args.from_topic
00088
00089 app = XdisplayImageTopic(from_topic=from_topic)
00090 rospy.spin()