簡體   English   中英

Python,如何以精度(uint8,uint16)將二維數組寫入二進制文件?

[英]Python, How to write a 2-d array to a binary File with precision (uint8, uint16)?

我希望有人可以向我解釋如何將二進制 output 寫入文本文件。

我知道在 matlab 中,它非常簡單,因為它具有“fwrite” function,其格式如下:fwrite(fileID,A,precision)

但是,我不確定如何將其翻譯為 python。 我目前將數據存儲在二維 numpy 數組中,並希望以與 matlab 相同的方式將其寫入文件。

我嘗試了以下方法:

#let Y be the numpy matrix
with open (filepath,'wb') as FileToWrite:
    np.array(Y.shape).tofile(FileToWrite)
    Y.T.tofile(FileToWrite)

然而,這並沒有導致預期的結果。 文件大小太大,數據格式不正確。 理想情況下,我也應該能夠將數據格式指定為 uint8 或 uint16。

任何幫助將不勝感激。

所以,我想通了。 解決方法如下。

#let Y be the numpy matrix
with open (filepath,'wb') as FileToWrite:
    np.asarray(Y, dtype=np.uint8).tofile(FileToWrite)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM