Search code examples
python-2.7opencvrospoint-clouds

How to add all object to an empty list in Python?


I created an empty list, output every loop, adding just one object. Once finish adding all object to the list, then repeat the same process as shown below.

I'm not sure how to add all objects in one loop?

This is outputs:

[u'person_0']
[u'person_0', u'chair_0']
[u'person_0', u'chair_0', u'chair_1']
[u'person_0', u'chair_0', u'chair_1', u'book_0']
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'bottle_0']

I only need the last output:

[u'person_0', u'chair_0', u'chair_1', u'book_0', u'bottle_0']

This is full code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rospy
import numpy
import tf

from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs import point_cloud2 as pc2
from sensor_msgs.msg import Image, PointCloud2
from dodo_detector.detection import SingleShotDetector
from dodo_detector_ros.msg import DetectedObject, DetectedObjectArray
import math

class Detector:

    def __init__(self):
        self._detector = SingleShotDetector('frozen_inference_graph.pb', 'mscoco_label_map.pbtxt', confidence=0.5)




        self._global_frame = rospy.get_param('~global_frame', None)
        self._tf_listener = tf.TransformListener()




        self._bridge = CvBridge()


        rospy.Subscriber("/camera/rgb/image_color", Image, self.image_callback)
        rospy.Subscriber('/camera/depth/points', PointCloud2, self.pc_callback)
        self._current_image = None
        self._current_pc = None


        self._imagepub = rospy.Publisher('~labeled_image', Image, queue_size=10)



        self._publishers = {None: (None, rospy.Publisher('~detected', DetectedObjectArray, queue_size=10))}




        self._tfpub = tf.TransformBroadcaster()
        rospy.loginfo('Ready to detect!')

    def image_callback(self, image):
        """Image callback"""

        self._current_image = image

    def pc_callback(self, pc):
        """Point cloud callback"""

        self._current_pc = pc

    def run(self):

        while not rospy.is_shutdown():

            if self._current_image is not None:
                try:


                    if self._global_frame is not None:
                        (trans, _) = self._tf_listener.lookupTransform('/' + self._global_frame, '/camera_link', rospy.Time(0))


                    scene = self._bridge.imgmsg_to_cv2(self._current_image, 'rgb8')
                    marked_image, objects = self._detector.from_image(scene)  # detect objects
                    self._imagepub.publish(self._bridge.cv2_to_imgmsg(marked_image, 'rgb8'))  # publish detection results


                    msgs = {}
                    for key in self._publishers:
                        msgs[key] = DetectedObjectArray()


                    my_tf_id = []
                    my_dis =[]
                    for obj_class in objects:

                        rospy.logdebug('Found ' + str(len(objects[obj_class])) + ' object(s) of type ' + obj_class)

                        for obj_type_index, coordinates in enumerate(objects[obj_class]):
#                     
                            rospy.logdebug('...' + obj_class + ' ' + str(obj_type_index) + ' at ' + str(coordinates))

                            ymin, xmin, ymax, xmax = coordinates
                            y_center = ymax - ((ymax - ymin) / 2)
                            x_center = xmax - ((xmax - xmin) / 2)

                            detected_object = DetectedObject()
                            detected_object.type.data = obj_class
                            detected_object.image_x.data = xmin
                            detected_object.image_y.data = ymin
                            detected_object.image_width.data = xmax - xmin
                            detected_object.image_height.data = ymax - ymin


                            publish_tf = False
                            if self._current_pc is None:
                                rospy.loginfo('No point cloud information available to track current object in scene')


                            else:

                                pc_list = list(pc2.read_points(self._current_pc, skip_nans=True, field_names=('x', 'y', 'z'), uvs=[(x_center, y_center)]))

                                if len(pc_list) > 0:

                                    publish_tf = True

                                    tf_id = obj_class + '_' + str(obj_type_index)        #object_number

                                    my_tf_id.append(tf_id)
                                    print my_tf_id




                                    detected_object.tf_id.data = tf_id



                                    point_x, point_y, point_z = pc_list[0] #point_z = x, point_x = y



                            if publish_tf:


                                object_tf = [point_z, -point_x, -point_y]

                                frame = 'cam_asus_link'

                                if self._global_frame is not None:
                                    object_tf = numpy.array(trans) + object_tf

                                    frame = self._global_frame

                                self._tfpub.sendTransform((object_tf), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), tf_id, frame)

                except CvBridgeError as e:
                    print(e)
                except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException) as e:
                    print(e)


if __name__ == '__main__':
    rospy.init_node('dodo_detector_ros', log_level=rospy.INFO)

    try:
        Detector().run()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')

Empty list line 82 (my_tf_id = []) and append to in it in line 119 (my_tf_id.append(tf_id)), finally use print my_tf_id in line 120

I am using python 2.7 , ROS, Opencv for detection of objects.

Please help me or make any suggestion.

Thank you in advance


Solution

  • You are printing the list inside the for loop. So everytime the loop iterates, it will print the list. Try to print my_tf_id outside the for loop