Skip to content

image callback in python very slow #509

Closed

Description

@rancheng

we are publishing an image in ROS2 with a resolution of 600 by 600. Using rclpy in Python, the callback is very slow. We ran the ros2/ros1 bridge and made a very similar ROS1 subscriber and the performance is perfect.

We tried using opensplice and fastRTPS, but since using the ROS2/ROS1 bridge callback works perfectly, we are confident it isn't the transport layer and the problem is probably with the python subscriber cash.

The cam2image example uses such a low resolution that the problem doesn't appear.

Activity

  1. dirk-thomas commented on Jun 20, 2018

    @dirk-thomas
    Member

    Please provide a reproducible example.

  2. added
    more-information-needed
    on Jul 5, 2018
  3. dirk-thomas commented on Jul 5, 2018

    @dirk-thomas
    Member

    Closing due to no response. Please feel free to comment with the requested information and this ticket can be reopened.

  4. Farrel7786729 commented on Jul 15, 2018

    @Farrel7786729

    I'm experiencing quite similar issue, although the enviroment is a bit different. My setup is VREP->ROS1->ROS2->rclpy. I receive decent fps with max resolution of 64*64. Anything more than that results in huge frame skips.

    It seems that that VREP->ROS1 works ok. So does ROS1->ROS2 bridge.

    With default setup my python code receives only each 10th image (my test resolution is 1024*512). When I set up QoS with KEEP_ALL policy, frameskip disappears, but my test module starts to "leak" memory, due to growing message queue, I assume. Although all frames are received, frame rate remains 1-2 fps. Here's my question on ros forum for reference https://answers.ros.org/question/296715/ros-image-message-rate-is-low/.

    Since environment is a bit tricky to reproduce, I'll try to come up with simple MWE.

    MWE:
    Publisher:
    ros2 run image_tools cam2image -x 1024 -y 512

    Subscriber:

    # coding=utf-8
    
    import rclpy
    import rclpy.node as node
    import cv2
    import numpy as np
    import sensor_msgs.msg as msg
    import std_msgs.msg as std_msg
    import rclpy.qos as qos
    
    import third_party.ros.ros as ros
    
    class TestDisplayNode(node.Node):
        def __init__(self):
            super().__init__('IProc_TestDisplayNode')
            self.__window_name = "img"
    
            #profile = qos.QoSProfile(history=qos.QoSHistoryPolicy.RMW_QOS_POLICY_HISTORY_KEEP_ALL)
            profile = qos.QoSProfile()
    
            self.sub = self.create_subscription(msg.Image, '/image', self.msg_callback, qos_profile=profile)
    
        def print_header_info(self, m : std_msg.Header):
            print("received image stamp {}".format(m.frame_id))
    
        def msg_callback(self, m : msg.Image):
            self.print_header_info(m.header)
            np_img = np.reshape(m.data, (m.height, m.width, 3)).astype(np.uint8)
            self.display(np_img)
    
        def display(self, img : np.ndarray):
            cv2.imshow(self.__window_name, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
            cv2.waitKey(1)
    
    def main():
        ros_core = ros.IProc_Ros2Core()
    
        node = TestDisplayNode()
    
        rclpy.spin(node)
    
        node.destroy_node()
        rclpy.shutdown()
    
    if __name__ == "__main__":
        main()
    

    Output:

    received image stamp 118
    received image stamp 126
    received image stamp 134
    received image stamp 141
    received image stamp 148
    received image stamp 155
    received image stamp 162
    received image stamp 169
    

    Note:

    1. Frame skip is a bit less then for vrep, although it's too much to be good enough to work with vision based applications.
    2. I do realize that I have output in the same thread, which increases latency, but I tried it with different client code, where processing was moved out to separate thread at first place, with exactly the same result.
  5. Farrel7786729 commented on Jul 25, 2018

    @Farrel7786729

    Looks like I've found an issue. I still need to run a couple of tests, though, just in order to be sure that nothing else causes delay.
    _image.py, which seems to be generated file, contains quite complex assert. For my distro it starts on line 199, and lines which are actually responsible for lag are 205, 206:

                assert \
                    ((isinstance(value, Sequence) or
                      isinstance(value, Set) or
                      isinstance(value, UserList)) and
                     not isinstance(value, str) and
                     not isinstance(value, UserString) and
                     all(isinstance(v, int) for v in value) and             ######## bottleneck
                     all(val >= 0 and val < 256 for val in value)), \   ########
                    "The 'data' field must be a set or sequence and each value of type 'int' and each unsigned integer in [0, 255]"
    

    Since it needs to be fixed in generator config, I cannot provide actual patch yet.

    UPDATE:
    Well, I was looking into that code quite late at night) It's the code for debugging version. Since I used default build command, I assume it's FAD behavior.

  6. rancheng commented on Jul 26, 2018

    @rancheng
    Author

    We have tried multiple things, QoS, change the cache size, etc. the thing we are doing is publishing a 600*600 image from ros2 in windows, and bridge it to ros1 in ubuntu.

    # rospy for the subscriber
    import rospy
    # ROS Image message
    from sensor_msgs.msg import Image
    # ROS Image message -> OpenCV2 image converter
    from cv_bridge import CvBridge, CvBridgeError
    # OpenCV2 for saving an image
    import cv2
    
    # Instantiate CvBridge
    bridge = CvBridge()
    
    i = 0
    
    def image_callback(msg):
        print("Received an image: {0}".format(i))
        # image_np = np.array(msg.data, np.uint8)
        # 	#image_np = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
        # image_np = image_np.reshape((msg.height, msg.width, 3)) #this might be  wrong order
        # cv2.imshow('image', image_np)
        # cv2.waitKey(1)
        try:
           # Convert your ROS Image message to OpenCV2
           cv2_img = bridge.imgmsg_to_cv2(msg, "bgr8")
        except CvBridgeError, e:
           print(e)
        else:
           #Save your OpenCV2 image as a jpeg
           cv2.imwrite('camera_image.jpeg', cv2_img)
           cv2.imshow('image', cv2_img)
           cv2.waitKey(1)
    
    def main():
        rospy.init_node('image_listener')
        # Define your image topic
        image_topic = "/vehicle_leftImage"
        # Set up your subscriber and define its callback
        rospy.Subscriber(image_topic, Image, image_callback)
        # Spin until ctrl + c
        rospy.spin()
    
    if __name__ == '__main__':
        main()

    Try publish a higher resolution, say 600*600 picture, to see that drop on fps.

  7. Farrel7786729 commented on Jul 26, 2018

    @Farrel7786729

    @rancheng, I won't be able to test your example untill monday. Just as an idea, did you try to run python interpreter with -O option? I did not notice that the code I mentioned was under if __debug__: last time. There's way more asserts which slow down execution.

    -O option allowed me to run ros2 run image_tools cam2image -x 1920 -y 1080 and receive images with allmost 30 fps (some frame skipping is still there, but it's quite ok: I've got 15 frames skipped for 1000 frame test run). Note, that I've switched off all output and image.reshape code, so only logging was still there, since it that particulat test numpy and cv output has become abottleneck.

  8. mikaelarguedas commented on Jul 30, 2018

    @mikaelarguedas
    Member

    did you try to run python interpreter with -O option? I did not notice that the code I mentioned was under if __debug__: last time.

    👍 We put all the setter checks in if __debug__ blocks to work around this type of performance issue. Note that this is only available as of ROS Bouncy (and not in Ardent).

  9. kervel commented on Nov 30, 2018

    @kervel

    btw, if others are bitten by this issue, a temporary workaround is creating a small binding using pybind11 using buffer protocol to access array members as numpy arrays. we do this for the data-intensive python nodes now.

    https://gist.github.com/kervel/75d81b8c34e45a19706c661b90d02548

  10. JacobJBeck commented on Feb 26, 2019

    @JacobJBeck

    Why is this issue closed? I'm still experiencing this. I thought it might be related to the DDS implementation (based on this issue), so I tested FastRTPS and OpenSplice using cam2image and my own python script which just shows a preview. I used ros2 topic hz /image to measure the rate, for which the results are shown below.

    DDS Resolution FPS
    FastRTPS 320x240 30.0
    FastRTPS 800x600 4.7
    FastRTPS 1920x1080 1.0
    OpenSplice 320x240 28.4
    OpenSplice 800x600 4.3
    OpenSplice 1920x1080 1.0

    Versions used:
    rclpy: 9efd331
    rmw_fastrtps: ea4fb7cfaa671a2118a7d54203c786d890d8ed38
    rmw_opensplice: 25287a690e8e91e6f56da51944829957c629708f

    edit: Using -O or -OO on the python side helps a little, but not much.
    edit2: These results are for QoS set to reliable. No images come through when using best effort on either rmw.

  11. dirk-thomas commented on Mar 27, 2019

    @dirk-thomas
    Member

    The performance bottle neck to convert the incoming message into a Python object has been resolved in ros2/rosidl_python#35.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    more-information-needed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions