如何将所有对象添加到 Python 中的空列表?
How to add all object to an empty list in Python?
我创建了一个空列表,输出每个循环,只添加一个对象。将所有对象添加到列表后,重复如下所示的相同过程。
我不确定如何在一个循环中添加所有对象?
这是输出:
[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']
我只需要最后一个输出:
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'bottle_0']
这是完整代码:
#!/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')
清空列表第 82 行 (my_tf_id = [
]) 并在第 119 行追加 (my_tf_id.append(tf_id)
),最后在第 120 行使用 print my_tf_id
我正在使用 python 2.7、ROS、Opencv 来检测对象。
请帮助我或提出任何建议。
提前致谢
您正在 for 循环中打印列表。所以每次循环迭代时,它都会打印列表。尝试 print my_tf_id
在 for 循环之外
我创建了一个空列表,输出每个循环,只添加一个对象。将所有对象添加到列表后,重复如下所示的相同过程。
我不确定如何在一个循环中添加所有对象?
这是输出:
[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']
我只需要最后一个输出:
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'bottle_0']
这是完整代码:
#!/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')
清空列表第 82 行 (my_tf_id = [
]) 并在第 119 行追加 (my_tf_id.append(tf_id)
),最后在第 120 行使用 print my_tf_id
我正在使用 python 2.7、ROS、Opencv 来检测对象。
请帮助我或提出任何建议。
提前致谢
您正在 for 循环中打印列表。所以每次循环迭代时,它都会打印列表。尝试 print my_tf_id
在 for 循环之外