Static cast equivalent in python

流过昼夜 提交于 2019-12-12 06:19:29

问题


My problem is the following:

I am using ROS and I am currently trying to read values from a PointCloud of a Kinect sensor. The values are of type PointCloud2 and PointCloud2.data holds the data of the PointCloud and is of type uint8[].

In my project I am currently using python and I have successfully registered and retrieved the data. My issue is that when trying to retrieve them python parses the uint8[] array as strings.

The current part of the script where I have the problem is the follwowing:

def PointCloud(self, PointCloud2):
    self.lock.acquire()
        for x in PointCloud2.data:
            print x
    self.lock.release()

I know that in c++ I can do something like

 std::cout << static_cast< int >( u );

To get the value of the unsigned integer. Is there a static cast equivalent to python?

In my case print x outputs ASCII characters. How could I retrieve the int value of that?

Cheers,

Panos


回答1:


Use struct.unpack to get the integer value encoded by the binary data in x.

print struct.unpack("!I", x)

(I'm assuming x contains a 4-byte integer in network byte order; consult the documentation for the struct module if you need a format other than !I.)


Update: I missed that you have an array of unsigned bytes; in that case, use

struct.unpack("B", x)



回答2:


Python doesn't support casting in any form; it's evil.

One version to achieve what you want is convert the data to hex:

print ['%02x' % e for e in PointCloud2.data]

or you can use the struct module to convert binary data into Python structures. If you want to process the data, you should look at Numpy which has an array type that you can create from a lot of different source.

For image processing, look at OpenCV. And for existing Python tools to work with Kinect, see Python- How to configure and use Kinect



来源:https://stackoverflow.com/questions/30104945/static-cast-equivalent-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!