python when there is no input for the subscriber it starts publishing error?/! how to solve it?

Viewed 28

I have provided the following python code,but the problem is that when it doesnot receive any input, it start showing error. how can i modify the code in a way that this error dosnot appear:

#!/usr/bin/env python from roslib import message import rospy import sensor_msgs.point_cloud2 as pc2 from sensor_msgs.msg import PointCloud2, PointField import numpy as np import ros_numpy from geometry_msgs.msg import Pose

#listener def listen():
    rospy.init_node('listen', anonymous=True)
    rospy.Subscriber("/Filtered_points_x", PointCloud2, callback_kinect)


def callback_kinect(data):
    pub = rospy.Publisher('lidar_distance',Pose, queue_size=10)
    data_lidar = Pose()
    xyz_array = ros_numpy.point_cloud2.pointcloud2_to_xyz_array(data)
    print(xyz_array)
    mini_data = min(xyz_array[:,0])
    print("mini_data", mini_data)
    data_lidar.position.x = mini_data  
    pub.publish(data_lidar) 
    print("data_points", data_lidar.position.x)
    height =  int (data.height / 2)
    middle_x = int (data.width / 2)
    middle = read_depth (middle_x, height, data)  # do stuff with middle


def read_depth(width, height, data) :
    if (height >= data.height) or (width >= data.width) :
        return -1
    data_out = pc2.read_points(data, field_names= ('x','y','z'), skip_nans=True, uvs=[[width, height]])
    int_data = next(data_out)
    rospy.loginfo("int_data " + str(int_data))
    return int_data

if __name__ == '__main__':
    try:
        listen()
        rospy.spin()
    except rospy.ROSInterruptException:
        pass

the following is the error that i mentioned:

[[ 7.99410915  1.36072445 -0.99567264]]
('mini_data', 7.994109153747559)
('data_points', 7.994109153747559)
[INFO] [1662109961.035894]: int_data (7.994109153747559, 1.3607244491577148, -0.9956726431846619)
[]
[ERROR] [1662109961.135572]: bad callback: <function callback_kinect at 0x7f9346d44230>
Traceback (most recent call last):
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
    cb(msg)
  File "/home/masoumeh/catkin_ws/src/yocs_velocity_smoother/test4/distance_from_pointcloud.py", line 27, in callback_kinect
    mini_data = min(xyz_array[:,0])
ValueError: min() arg is an empty sequence
1 Answers

The code is still receiving input, but specifically it’s receiving an empty array. You’re then trying to splice the empty array, causing the error. Instead you should check that the array has elements before the line min(xyz_array[:,0]). It can be as simple as:

if xyz_array == []:
    return

As another note, you’re creating a publisher in the callback. You shouldn’t do this as a new publisher will be created every time it gets called. Instead create it as a global variable.

Related