2016-05-12 87 views
-1

這是我第一次使用二進制文件直接與我一起工作。在Python中解釋二進制數據

我使用Python 2.7

我試圖用一個大的二進制文件,指定圖像的每個像素的經/緯度。

使用此代碼:open('input', 'rb').read(50)

文件看起來是這樣的: \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 ...

在讀我的文件給出瞭解碼以下信息,但我不確定如何應用它們:

這些文件採用LSBF字節順序。文件以2個4字節整數值開始,給出文件的像素和行(x,y)大小。在文件成功之後,成對的元素是經度和緯度的2字節整數值乘以100並截斷(例如75.324E是「-7532」)。

感謝您的任何幫助。

請注意,最終這樣做的原因是根據lat/long繪製/更改圖像,而不是像素#,以防有人想知道。

+1

您可以將其轉換爲NumPy數組。那會很方便嗎?順便說一句,你使用Python 2或Python 3? –

+0

python中的兩個主要工具是['struct'](https://docs.python.org/2/library/struct.html)模塊和['numpy.fromfile'](http:// docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.fromfile.html)。鑑於大量的數據,numpy可能是最簡單和最快的。 [Here's](http://stackoverflow.com/questions/14245094/how-to-read-part-of-binary-file-with-numpy)一個例子。如果您遇到問題,我建議您嘗試一下併發布具體問題。 – tom10

+0

很抱歉編輯說使用Python 2.7。 – MattS

回答

0

通常,在使用二進制文件時,您會想要使用包和解包(https://docs.python.org/2/library/struct.html)函數。這將允許您控制數據的永久性以及數據類型。在特定情況下,你可能會想先讀取頭信息,像

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 

    ... 

以上未實際運行或測試,只是想給你一個方法的一般意義。