简体   繁体   English

在 Python 中解释二进制数据

[英]interpreting binary data in Python

I am using Python 2.7我正在使用 Python 2.7

I am trying to use a large binary file that specifies the latitude/longitude of each pixel of an image.我正在尝试使用一个大型二进制文件来指定图像每个像素的纬度/经度。

Using this code: open('input', 'rb').read(50)使用此代码: open('input', 'rb').read(50)

The file looks like this: \\x80\\x0c\\x00\\x00\\x00\\x06\\x00\\x00.\\x18\\xca\\xe4.\\x18\\xcc\\xe4.\\x18\\xcf\\xe4.\\x18\\xd1\\xe4.\\x18\\xd3\\xe4.\\x18\\xd5\\xe4.\\x18\\xd7\\xe4.\\x18\\xd9\\xe4/\\x18\\xdb\\xe4/\\x18\\xdd\\xe4/\\x18 ...该文件如下所示: \\x80\\x0c\\x00\\x00\\x00\\x06\\x00\\x00.\\x18\\xca\\xe4.\\x18\\xcc\\xe4.\\x18\\xcf\\xe4.\\x18\\xd1\\xe4.\\x18\\xd3\\xe4.\\x18\\xd5\\xe4.\\x18\\xd7\\xe4.\\x18\\xd9\\xe4/\\x18\\xdb\\xe4/\\x18\\xdd\\xe4/\\x18 ...

The read-me for the file gives the following information for decoding but I am unsure of how to apply them:该文件的自述文件提供了以下解码信息,但我不确定如何应用它们:

The files are in LSBF byte order.这些文件采用 LSBF 字节顺序。 Files start with 2 4-byte integer values giving the pixel and line (x,y) size of the file.文件以 2 个 4 字节整数值开头,给出文件的像素和行 (x,y) 大小。 After the files have succeeding pairs of elements are 2-byte integer values of latitude and longitude multiplied 100 and truncated (eg 75.324 E is "-7532").在文件具有成功的元素对之后,纬度和经度的 2 字节整数值乘以 100 并被截断(例如 75.324 E 是“-7532”)。

Thanks for any help.谢谢你的帮助。

Note the reason for doing this ultimately would be to draw/alter an image based on lat/long and not the pixel # in case anyone was wondering.请注意,这样做的最终原因是基于纬度/经度而不是像素#绘制/更改图像,以防万一有人想知道。

Generally when working with binary files you'll want to use the pack and unpack ( https://docs.python.org/2/library/struct.html ) functions.通常,在处理二进制文件时,您需要使用打包和解包 ( https://docs.python.org/2/library/struct.html ) 函数。 That will allow you to control the endianess of the data as well as the data types.这将允许您控制数据的字节序以及数据类型。 In your specific case you'll probably want to read the header info first, something like在您的特定情况下,您可能想先阅读标题信息,例如

with open('input', 'rb') as fp:

    # read the header bytes to get the number of elements

    header_bytes = fp.read(8)

    # convert the bytes to two unsigned integers. 

    x, y = unpack("II", header_bytes)

    # Loop through the file getting the rest of the data
    # read Y lines of X pixels

    ...

The above was not actually run or test, just trying to give you a general sense of an approach.以上并不是实际运行或测试,只是试图让您大致了解一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM