Python Forum
Some help with my first python class and importing ....im making a lidar program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some help with my first python class and importing ....im making a lidar program
#1
Hello all,
wow, im tired and have few solutions in the morning now...ok....well maybe i will find some help here.
I am making a personal lidar "fish viewer" for the dock. or pier?
and i have a simple problem in python....
Traceback (most recent call last):
  File "/usr/share/fishviewer/A_Fish_Detecting_LIDAR_Program.py", line 190, in <module>
    cloud2 = generator()
             ^^^^^^^^^^^
  File "/usr/share/fishviewer/A_Fish_Detecting_LIDAR_Program.py", line 183, in generator
    cloud = projectLaser(msg=scan_in)
            ^^^^^^^^^^^^
NameError: name 'projectLaser' is not defined
I will lay out where it is importing from and that i just dont know how to type the import:

Btw: what i am building ----
   
   

Oh, so also the Program with the import error of the class or somebit:
##################################################################################
#!/usr/bin/env python3
##################################################################################
import rospy
from sensor_msgs.msg import LaserScan
import laser_geometry
import laser_geometry.laser_geometry as lg
import math
import numpy as np
import time
from sensor_msgs.msg import PointCloud
from geometry_msgs.msg import Point32
import std_msgs.msg
import sys
from sensor_msgs.msg import PointCloud2
import std_msgs.msg
import sensor_msgs.point_cloud2 as pcl2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import mpl_toolkits.mplot3d
##################################################################################
###### rospy  #################################################################
##################################################################################
rospy.init_node('fishviewer')
##################################################################################
###### LaserScan #################################################################
##################################################################################
def laserscan():
    msg = LaserScan()
    msg.angle_min = -1.57
    msg.angle_min = -1.57
    msg.angle_max = 1.57
    msg.angle_increment = 0.1
    msg.time_increment = 0.001
    msg.scan_time = 0.05
    msg.range_min = 0.0
    msg.range_max = 10.0
    msg.ranges = [1.0] * int((msg.angle_max - msg.angle_min) / msg.angle_increment)
    msg.intensities = [1] * len(msg.ranges)

    return msg
##################################################################################
##### LaserProjection -- convert scan to point cloud 2 ###############################################################################
##################################################################################
class LaserProjection:
    LASER_SCAN_INVALID   = -1.0
    LASER_SCAN_MIN_RANGE = -2.0
    LASER_SCAN_MAX_RANGE = -3.0
    class ChannelOption:
        NONE      = 0x00 # Enable no channels
        INTENSITY = 0x01 # Enable "intensities" channel
        INDEX     = 0x02 # Enable "index"       channel
        DISTANCE  = 0x04 # Enable "distances"   channel
        TIMESTAMP = 0x08 # Enable "stamps"      channel
        VIEWPOINT = 0x10 # Enable "viewpoint"   channel
        DEFAULT   = (INTENSITY | INDEX)
    def __init__(self):
        self.__angle_min = 0.0
        self.__angle_max = 0.0
        self.__cos_sin_map = np.array([[]])
    def projectLaser(self, scan_in,
            range_cutoff=-1.0, channel_options=ChannelOption.DEFAULT):
        return self.__projectLaser(scan_in, range_cutoff, channel_options)
    def __projectLaser(self, scan_in, range_cutoff, channel_options):
        N = len(scan_in.ranges)
        ranges = np.array(scan_in.ranges)
        if (self.__cos_sin_map.shape[1] != N or
            self.__angle_min != scan_in.angle_min or
            self.__angle_max != scan_in.angle_max):
            rospy.logdebug("No precomputed map given. Computing one.")
            self.__angle_min = scan_in.angle_min
            self.__angle_max = scan_in.angle_max
            angles = scan_in.angle_min + np.arange(N) * scan_in.angle_increment
            self.__cos_sin_map = np.array([np.cos(angles), np.sin(angles)])
        output = ranges * self.__cos_sin_map
        # Set the output cloud accordingly
        cloud_out = PointCloud2()
        fields = [pc2.PointField() for _ in range(3)]
        fields[0].name = "x"
        fields[0].offset = 0
        fields[0].datatype = pc2.PointField.FLOAT32
        fields[0].count = 1
        fields[1].name = "y"
        fields[1].offset = 4
        fields[1].datatype = pc2.PointField.FLOAT32
        fields[1].count = 1
        fields[2].name = "z"
        fields[2].offset = 8
        fields[2].datatype = pc2.PointField.FLOAT32
        fields[2].count = 1
        idx_intensity = idx_index = idx_distance =  idx_timestamp = -1
        idx_vpx = idx_vpy = idx_vpz = -1
        offset = 12
        if (channel_options & self.ChannelOption.INTENSITY and
            len(scan_in.intensities) > 0):
            field_size = len(fields)
            fields.append(pc2.PointField())
            fields[field_size].name = "intensity"
            fields[field_size].datatype = pc2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_intensity = field_size
        if channel_options & self.ChannelOption.INDEX:
            field_size = len(fields)
            fields.append(pc2.PointField())
            fields[field_size].name = "index"
            fields[field_size].datatype = pc2.PointField.INT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_index = field_size
        if channel_options & self.ChannelOption.DISTANCE:
            field_size = len(fields)
            fields.append(pc2.PointField())
            fields[field_size].name = "distances"
            fields[field_size].datatype = pc2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_distance = field_size
        if channel_options & self.ChannelOption.TIMESTAMP:
            field_size = len(fields)
            fields.append(pc2.PointField())
            fields[field_size].name = "stamps"
            fields[field_size].datatype = pc2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_timestamp = field_size
        if channel_options & self.ChannelOption.VIEWPOINT:
            field_size = len(fields)
            fields.extend([pc2.PointField() for _ in range(3)])
            fields[field_size].name = "vp_x"
            fields[field_size].datatype = pc2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpx = field_size
            field_size += 1
            fields[field_size].name = "vp_y"
            fields[field_size].datatype = pc2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpy = field_size
            field_size += 1
            fields[field_size].name = "vp_z"
            fields[field_size].datatype = pc2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpz = field_size
        if range_cutoff < 0:
            range_cutoff = scan_in.range_max
        else:
            range_cutoff = min(range_cutoff, scan_in.range_max)
        points = []
        for i in range(N):
            ri = scan_in.ranges[i]
            if ri < range_cutoff and ri >= scan_in.range_min:
                point = output[:, i].tolist()
                point.append(0)
                if idx_intensity != -1:
                    point.append(scan_in.intensities[i])
                if idx_index != -1:
                    point.append(i)
                if idx_distance != -1:
                    point.append(scan_in.ranges[i])
                if idx_timestamp != -1:
                    point.append(i * scan_in.time_increment)
                if idx_vpx != -1 and idx_vpy != -1 and idx_vpz != -1:
                    point.extend([0 for _ in range(3)])
                points.append(point)
        cloud = pc2.create_cloud(scan_in.header, fields, points)
        return cloud
##################################################################################
####################################################################################
##################################################################################
def generator():
  #while true:
    msg = laserscan()
    cloud = projectLaser(msg=scan_in)
    point_generator_seafloor = pcl2.read_points(cloud)
    cloud = pcl2.read_points_list(cloud)
    return cloud2
##################################################################################
###### plotting  #################################################################
##################################################################################
cloud2 = generator()
def plotter():
    # Creating figure
    fig = plt.figure(figsize = (16, 9))
    ax = plt.axes(projection ="3d")
    ax.grid(b = True, color ='grey',
        linestyle ='-.', linewidth = 0.3,
        alpha = 0.2)
    my_cmap = plt.get_cmap('hsv')
    sctt = ax.scatter3D(cloud2[0], cloud2[1], cloud2[2],
                    alpha = 0.8,
                    c = (cloud2[0] + cloud2[1] + cloud2[2]),
                    cmap = my_cmap,
                    marker ='0(c='+z+' depth')
    plt.title("Lidar Fish Viewer")
    ax.set_zlabel('DEPTH', fontweight ='bold')
    fig.colorbar(sctt, ax = ax, shrink = 0.5, aspect = 5)
    plt.show()
    return fig,ax,sctt
#########################################
def plot_updater():
    cloud = generator()
    ax.relim()
    ax.autoscale()
    cloud.set_xdata(cloud[0])
    cloud.set_ydata(cloud[1])
    cloud.set_3d_properties(cloud[2])
    return ax, cloud
fig = plotter() # instantiate figure and plot
########################################

plot_updater()

rospy.spin()
Please help!!!!

ALSO ---
The definition to import comes in module laser_geometry:
http://wiki.ros.org/laser_geometry

AND---
the definition has a python file itself....so i plugged it in making the import issue now a class issue...if you follow:
http://docs.ros.org/en/melodic/api/laser...ource.html


I have ROS melodic on a raspberry pi with lidar LD07 available on amazon, however, the question just needs knowledge of how to import or run infile....

thank you again for reading an bearing with me....
what about a way to import LaserProjection() as the best answer....???
Reply
#2
Scope problem. You define the function projectLaser() within the class LaserProjection. By doing this you need to create an instance of the LaserProjection class then call projectLaser on that.
jttolleson likes this post
Reply
#3
Yup ---- you make sense - i have followed and the program is now working much harder....i cleared up some typos aswell:


A_Fish_Detecting_LIDAR_Program.py
##################################################################################
#!/usr/bin/env python3
##################################################################################
import rospy
from sensor_msgs.msg import LaserScan
import laser_geometry
import laser_geometry.laser_geometry as lg
import math
import numpy as np
import time
from sensor_msgs.msg import PointCloud
from geometry_msgs.msg import Point32
import std_msgs.msg
import sys
from sensor_msgs.msg import PointCloud2
import std_msgs.msg
import sensor_msgs.point_cloud2 as pcl2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import mpl_toolkits.mplot3d
##################################################################################
###### rospy  #################################################################
##################################################################################
rospy.init_node('fishviewer')
##################################################################################
###### LaserScan #################################################################
##################################################################################
def laserscan():
    msg = LaserScan()
    msg.angle_min = -1.57
    msg.angle_min = -1.57
    msg.angle_max = 1.57
    msg.angle_increment = 0.1
    msg.time_increment = 0.001
    msg.scan_time = 0.05
    msg.range_min = 0.0
    msg.range_max = 10.0
    msg.ranges = [1.0] * int((msg.angle_max - msg.angle_min) / msg.angle_increment)
    msg.intensities = [1] * len(msg.ranges)

    return msg
##################################################################################
##### LaserProjection -- convert scan to point cloud 2 ###############################################################################
##################################################################################
class LaserProjection:
    LASER_SCAN_INVALID   = -1.0
    LASER_SCAN_MIN_RANGE = -2.0
    LASER_SCAN_MAX_RANGE = -3.0
    class ChannelOption:
        NONE      = 0x00 # Enable no channels
        INTENSITY = 0x01 # Enable "intensities" channel
        INDEX     = 0x02 # Enable "index"       channel
        DISTANCE  = 0x04 # Enable "distances"   channel
        TIMESTAMP = 0x08 # Enable "stamps"      channel
        VIEWPOINT = 0x10 # Enable "viewpoint"   channel
        DEFAULT   = (INTENSITY | INDEX)
    def __init__(self,msg):
        self.__angle_min = 0.0
        self.__angle_max = 0.0
        self.__cos_sin_map = np.array([[]])
    def projectLaser(self, msg,
            range_cutoff=-1.0, channel_options=ChannelOption.DEFAULT):
        return self.__projectLaser(msg, range_cutoff, channel_options)
    def __projectLaser(self, msg, range_cutoff, channel_options):
        N = len(msg.ranges)
        ranges = np.array(msg.ranges)
        if (self.__cos_sin_map.shape[1] != N or
            self.__angle_min != msg.angle_min or
            self.__angle_max != msg.angle_max):
            rospy.logdebug("No precomputed map given. Computing one.")
            self.__angle_min = msg.angle_min
            self.__angle_max = msg.angle_max
            angles = msg.angle_min + np.arange(N) * msg.angle_increment
            self.__cos_sin_map = np.array([np.cos(angles), np.sin(angles)])
        output = ranges * self.__cos_sin_map
        # Set the output cloud accordingly
        cloud = PointCloud2()
        fields = [pcl2.PointField() for _ in range(3)]
        fields[0].name = "x"
        fields[0].offset = 0
        fields[0].datatype = pcl2.PointField.FLOAT32
        fields[0].count = 1
        fields[1].name = "y"
        fields[1].offset = 4
        fields[1].datatype = pcl2.PointField.FLOAT32
        fields[1].count = 1
        fields[2].name = "z"
        fields[2].offset = 8
        fields[2].datatype = pcl2.PointField.https://python-forum.io/images/smilies/shy.pngFLOAT32
        fields[2].count = 1
        idx_intensity = idx_index = idx_distance =  idx_timestamp = -1
        idx_vpx = idx_vpy = idx_vpz = -1
        offset = 12
        if (channel_options & self.ChannelOption.INTENSITY and
            len(msg.intensities) > 0):
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "intensity"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_intensity = field_size
        if channel_options & self.ChannelOption.INDEX:
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "index"
            fields[field_size].datatype = pcl2.PointField.INT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_index = field_size
        if channel_options & self.ChannelOption.DISTANCE:
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "distances"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_distance = field_size
        if channel_options & self.ChannelOption.TIMESTAMP:
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "stamps"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_timestamp = field_size
        if channel_options & self.ChannelOption.VIEWPOINT:
            field_size = len(fields)
            fields.extend([pcl2.PointField() for _ in range(3)])
            fields[field_size].name = "vp_x"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpx = field_size
            field_size += 1
            fields[field_size].name = "vp_y"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpy = field_size
            field_size += 1
            fields[field_size].name = "vp_z"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpz = field_size
        if range_cutoff < 0:
            range_cutoff = msg.range_max
        else:
            range_cutoff = min(range_cutoff, msg.range_max)
        points = []
        for i in range(N):
            ri = msg.ranges[i]
            if ri < range_cutoff and ri >= msg.range_min:
                point = output[:, i].tolist()
                point.append(0)
                if idx_intensity != -1:
                    point.append(msg.intensities[i])
                if idx_index != -1:
                    point.append(i)
                if idx_distance != -1:
                    point.append(msg.ranges[i])
                if idx_timestamp != -1:
                    point.append(i * msg.time_increment)
                if idx_vpx != -1 and idx_vpy != -1 and idx_vpz != -1:
                    point.extend([0 for _ in range(3)])
                points.append(point)
        cloud = pcl2.create_cloud(msg.header, fields, points)
        cloud = pc2.read_points_list(cloud)
        return cloud
##################################################################################
####################################################################################
##################################################################################
def generator():
  #while true:
    msg = laserscan()
    print ('laserscan: '+str(msg))
    cloud = LaserProjection(msg)
    print ('laserprojection in mem: '+str(cloud))
    t = 0
    xyz = []
    print (str(cloud.read()))
    for vaper in cloud:
        vaper = cloud.readline()
        t = t + 1
        xyz = xyz.append(vaper)
    return xyz
##################################################################################
###### plotting  #################################################################
##################################################################################
xyz = generator()
def plotter():
    # Creating figure
    fig = plt.figure(figsize = (16, 9))
    ax = plt.axes(projection ="3d")
    ax.grid(b = True, color ='grey',
        linestyle ='-.', linewidth = 0.3,
        alpha = 0.2)
    my_cmap = plt.get_cmap('hsv')
    sctt = ax.scatter3D(xyz[0], xyz[1], xyz[2],
                    alpha = 0.8,
                    c = (xyz[0] + xyz[1] + xyz[2]),
                    cmap = my_cmap,
                    marker ='0(c='+xyz[2]+' depth')
    plt.title("Lidar Fish Viewer")
    ax.set_zlabel('DEPTH', fontweight ='bold')
    fig.colorbar(sctt, ax = ax, shrink = 0.5, aspect = 5)
    plt.show()
    return fig,ax,sctt
#########################################
def plot_updater():
    cloud = generator()
    ax.relim()
    ax.autoscale()
    cloud.set_xdata(cloud[0])
    cloud.set_ydata(cloud[1])
    cloud.set_3d_properties(cloud[2])
    return ax, cloud
fig = plotter() # instantiate figure and plot
########################################

plot_updater()

rospy.spin()
Reply
#4
Why are you doing this?
        self.__angle_min = 0.0 
A single leading underscore is the convention for marking an attribute for internal use only (pseudo private). Leading with a doulbe underscore should be saved for the special case where subclasses of a class should not have access to the attribute. self.__angle_min = 0 creates an attribute with a mangled name _LaserProjection__angle_min. In the LaserProjection class, self.__angle_min will return this variable, but it will generate an error in a subclass.
class LaserProjection:
    def __init__(self):
        self.__angle_min = 0

    def __str__(self):
        return f"Angles = {self.__angle_min}"


class LaserProjectionSubclass(LaserProjection):
    def __init__(self):
        self.__angle_max = 0

    def __str__(self):
        return f"Angles = {self.__angle_min}, {self.__angle_max}"


print(LaserProjection())
print(LaserProjectionSubclass())
Error:
Angles = 0 Traceback (most recent call last): File "...test.py", line 18, in <module> print(LaserProjectionSubclass()) File "...test.py", line 14, in __str__ return f"Angles = {self.__angle_min}, {self.__angle_max}" AttributeError: 'LaserProjectionSubclass' object has no attribute '_LaserProjectionSubclass__angle_min'. Did you mean: '_LaserProjectionSubclass__angle_max'?
Why do you do this?
import laser_geometry
import laser_geometry.laser_geometry as lg
If you only use laser_geometry.laser_geometry, you do not need to also import laser_geometry.

Some vertical whitespace will make your program much easier to read. Two blank lines before a class or a function is suggested.
jttolleson likes this post
Reply
#5
so, yes ... my imports were, well, not perfect.
and I "did it that way" because that is the same definition as the webpage or the what a LaserProjection() is supposed to be
i believe i should leave it at zero bc i am actually scanning too, so i dont need to affect the data more.


also, i really like fishing and seeing them in color, oh my...
Reply
#6
updated Code:

a "one shot graph"----realtime otw...

##################################################################################
#!/usr/bin/env python3
##################################################################################
import rospy
from sensor_msgs.msg import LaserScan
import laser_geometry.laser_geometry as lg
import math
import numpy as np
import time
import sensor_msgs.point_cloud2 as pcl2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import mpl_toolkits.mplot3d
##################################################################################
###### rospy  #################################################################
##################################################################################
rospy.init_node('fishviewer')
##################################################################################
###### LaserScan #################################################################
##################################################################################
def laserscan():
    msg = LaserScan()
    msg.angle_min = -1.57
    msg.angle_min = -1.57
    msg.angle_max = 1.57
    msg.angle_increment = 0.1
    msg.time_increment = 0.001
    msg.scan_time = 0.05
    msg.range_min = 0.0
    msg.range_max = 10.0
    msg.ranges = [1.0] * int((msg.angle_max - msg.angle_min) / msg.angle_increment)
    msg.intensities = [1] * len(msg.ranges)

    return msg
##################################################################################
##### LaserProjection -- convert scan to point cloud 2 ###############################################################################
##################################################################################
class LaserProjection:
    LASER_SCAN_INVALID   = -1.0
    LASER_SCAN_MIN_RANGE = -2.0
    LASER_SCAN_MAX_RANGE = -3.0
    class ChannelOption:
        NONE      = 0x00 # Enable no channels
        INTENSITY = 0x01 # Enable "intensities" channel
        INDEX     = 0x02 # Enable "index"       channel
        DISTANCE  = 0x04 # Enable "distances"   channel
        TIMESTAMP = 0x08 # Enable "stamps"      channel
        VIEWPOINT = 0x10 # Enable "viewpoint"   channel
        DEFAULT   = (INTENSITY | INDEX)
    def __init__(self,msg):
        self.__angle_min = 0.0
        self.__angle_max = 0.0
        self.__cos_sin_map = np.array([[]])
    def projectLaser(self, msg,
            range_cutoff=-1.0, channel_options=ChannelOption.DEFAULT):
        return self.__projectLaser(msg, range_cutoff, channel_options)
    def __projectLaser(self, msg, range_cutoff, channel_options):
        N = len(msg.ranges)
        ranges = np.array(msg.ranges)
        if (self.__cos_sin_map.shape[1] != N or
            self.__angle_min != msg.angle_min or
            self.__angle_max != msg.angle_max):
            rospy.logdebug("No precomputed map given. Computing one.")
            self.__angle_min = msg.angle_min
            self.__angle_max = msg.angle_max
            angles = msg.angle_min + np.arange(N) * msg.angle_increment
            self.__cos_sin_map = np.array([np.cos(angles), np.sin(angles)])
        output = ranges * self.__cos_sin_map
        # Set the output cloud accordingly
        cloud = PointCloud2()
        fields = [pcl2.PointField() for _ in range(3)]
        fields[0].name = "x"
        fields[0].offset = 0
        fields[0].datatype = pcl2.PointField.FLOAT32
        fields[0].count = 1
        fields[1].name = "y"
        fields[1].offset = 4
        fields[1].datatype = pcl2.PointField.FLOAT32
        fields[1].count = 1
        fields[2].name = "z"
        fields[2].offset = 8
        fields[2].datatype = pcl2.PointField.FLOAT32
        fields[2].count = 1
        idx_intensity = idx_index = idx_distance =  idx_timestamp = -1
        idx_vpx = idx_vpy = idx_vpz = -1
        offset = 12
        if (channel_options & self.ChannelOption.INTENSITY and
            len(msg.intensities) > 0):
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "intensity"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_intensity = field_size
        if channel_options & self.ChannelOption.INDEX:
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "index"
            fields[field_size].datatype = pcl2.PointField.INT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_index = field_size
        if channel_options & self.ChannelOption.DISTANCE:
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "distances"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_distance = field_size
        if channel_options & self.ChannelOption.TIMESTAMP:
            field_size = len(fields)
            fields.append(pcl2.PointField())
            fields[field_size].name = "stamps"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_timestamp = field_size
        if channel_options & self.ChannelOption.VIEWPOINT:
            field_size = len(fields)
            fields.extend([pcl2.PointField() for _ in range(3)])
            fields[field_size].name = "vp_x"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpx = field_size
            field_size += 1
            fields[field_size].name = "vp_y"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpy = field_size
            field_size += 1
            fields[field_size].name = "vp_z"
            fields[field_size].datatype = pcl2.PointField.FLOAT32
            fields[field_size].offset = offset
            fields[field_size].count = 1
            offset += 4
            idx_vpz = field_size
        if range_cutoff < 0:
            range_cutoff = msg.range_max
        else:
            range_cutoff = min(range_cutoff, msg.range_max)
        points = []
        for i in range(N):
            ri = msg.ranges[i]
            if ri < range_cutoff and ri >= msg.range_min:
                point = output[:, i].tolist()
                point.append(0)
                if idx_intensity != -1:
                    point.append(msg.intensities[i])
                if idx_index != -1:
                    point.append(i)
                if idx_distance != -1:
                    point.append(msg.ranges[i])
                if idx_timestamp != -1:
                    point.append(i * msg.time_increment)
                if idx_vpx != -1 and idx_vpy != -1 and idx_vpz != -1:
                    point.extend([0 for _ in range(3)])
                points.append(point)
        cloud = pcl2.create_cloud(msg.header, fields, points)
        x = []
        y = []
        z = []
        xyz = []
        for vapor in pcl2.read_points(msg, skip_nans=True):
            pt_x = vapor[0]
            x = x.append(pt_x)
            pt_y = vapor[1]
            y = y.append(pt_y)
            pt_z = vapor[2]
            z = z.append(pt_z)
        xyz = x, y, z
        return xyz
##################################################################################
####################################################################################
##################################################################################
def generator():
    msg = laserscan()
    xyz = LaserProjection(msg)
    return xyz
##################################################################################
###### plotting  #################################################################
##################################################################################
def plotter(xyz):
    # Creating figure
    fig = plt.figure(figsize = (16, 9))
    ax = plt.axes(projection ="3d")
    ax.grid(b = True, color ='grey',
        linestyle ='-.', linewidth = 0.3,
        alpha = 0.2)
    my_cmap = plt.get_cmap('hsv')
    sctt = ax.scatter3D(xyz[0], xyz[1], xyz[2],
                    alpha = 0.8,
                    c = (xyz[0] + xyz[1] + xyz[2]),
                    cmap = my_cmap,
                    marker ='0(c='+xyz[2]+' depth')
    plt.title("Lidar Fish Viewer")
    ax.set_zlabel('DEPTH', fontweight ='bold')
    fig.colorbar(sctt, ax = ax, shrink = 0.5, aspect = 5)
    plt.show()
    return fig,ax,sctt
#########################################
xyz = generator()
print ('points:'+str(xyz))https://python-forum.io/images/smilies/arrow.png
time.sleep(9)
plotter(xyz)
rospy.spin()
Reply
#7
Well, now --
The program health has gone up, dramatically and I am going to see a plot sometime....

right now i have this as possibly my last error:
   
   

SO, i need to read these object to strings or int.....any help again....???
Reply
#8
well, I have been learning a lot.... at first i new nothing about serial communication in python now i am learning more....

this is the actual answer, not the whole code to my question about, well, now, importing.

from sensor_msgs.msg import LaserScan
import laser_geometry.laser_geometry as lg   #i had some difficulty here.....
from laser_geometry import LaserProjection     #much more here
import sensor_msgs.point_cloud2 as pcl2          #glad it is resolved some

msg = laserscan()  # return value msg from laserscan()
lp = lg.LaserProjection()  # make lp out of modules
pointcloud2 = lp.projectLaser(msg)  #use lp to get a pcl from scan
pointlist = pcl2.read_points_list(pointcloud2)  
print (pointlist)

Attached Files

Thumbnail(s)
   
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Lidar in python - Quaternions, Angular Velocity, Linear Accelleration? jttolleson 2 546 Nov-27-2023, 02:05 AM
Last Post: jttolleson
  python standard way of importing library mg24 1 915 Nov-15-2022, 01:41 AM
Last Post: deanhystad
  My code displays too much output when importing class from a module lil_e 4 1,167 Oct-22-2022, 12:56 AM
Last Post: Larz60+
  making variables in my columns and rows in python kronhamilton 2 1,630 Oct-31-2021, 10:38 AM
Last Post: snippsat
Smile Help making number analysis program Dainer 2 1,770 Jun-24-2021, 09:55 PM
Last Post: jefsummers
  Importing issues with base class for inheritance riccardoob 5 4,723 May-19-2021, 05:18 PM
Last Post: snippsat
  newbie question....importing a created class ridgerunnersjw 5 2,679 Oct-01-2020, 07:59 PM
Last Post: ridgerunnersjw
  Importing Program Wide JarredAwesome 4 2,198 Sep-07-2020, 04:34 PM
Last Post: JarredAwesome
  importing a list of numbers into python script barrypyth 8 4,612 Aug-22-2020, 09:10 PM
Last Post: barrypyth
  Importing python data to Textfile or CSV yanDvator 0 1,763 Aug-02-2020, 06:58 AM
Last Post: yanDvator

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020