【问题标题】:Write Real Raw Binary File from Python从 Python 编写真正的原始二进制文件
【发布时间】:2019-07-26 16:10:21
【问题描述】:

我尝试了多种不同的变体,但由于某种原因,我不断将无效的二进制数字(人类可读)输出到文件中:

img_array = np.asarray(imageio.imread('test.png', as_gray=True), dtype='int8')
img_array.astype('int8').tofile("test.dat")

但这不会产生有效的二进制文件。一旦文件被读入 Verilog tb,它就会抱怨无效的二进制数字,当我打开文件时,我会看到一堆数字和其他字符。只是它似乎翻译不正确。

更新: 运行后

print(img_array)
print(img_array.tobytes())

我可以看到 int 值“43”正在被转换为“+”,而我希望是“2B”。它似乎只是将某些值打印到 ASCII。这是一个简单的例子:

x = np.array([[0, 9], [2, 3]], dtype='uint8')
print(x.astype('uint8'))
print(x.tobytes())

输出是:

[[0 9]

[2 3]]

b'\x00\t\x02\x03'

我该如何解决这个问题?

任何帮助将不胜感激。

我尝试过的其他解决方案:

Write a “string” as raw binary into a file Python

Write a raw binary file with NumPy array data

【问题讨论】:

    标签: python python-3.x numpy binary


    【解决方案1】:

    https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tobytes.html

    img_array = np.asarray(imageio.imread('test.png', as_gray=True), dtype='int8')
    img_array = img_array.astype('int8')
    
    with open('test.dat', 'wb') as f:
        f.write(img_array.tobytes())
    

    【讨论】:

    • 嗯.. 这似乎对我不起作用。正如您在文档链接中引用的那样,我将您的“to_bytes()”调用更改为“tobytes()”,因为 numpy ndarray 没有 to_bytes() 方法。即使这样,输出填充也包含许多数字。似乎也有一些冗余,因为在第一行中,我声明了“dtype='int8'”,然后您使用“astype('int8')”。
    • 抱歉打错了。 tobytes 将您的内容编码为字节字符串。现在,将其读回并解码,您将看到您的数组。
    • 我在我的问题中添加了一个更新,指出了问题所在。不幸的是,我没有使用 pythons 方法来读取和解码。此原始数据正在传输到 verilog tb
    【解决方案2】:

    这提供了一个可行的解决方案,可以转换为一串十六进制值。这不完全是我想要的,但它创造了一个有效的解决方法,因为我的原始问题尚未得到回答。虽然我没有找到这个解决方案,所以我可以参考它的来源,但无论如何我都会在这里分享。显然这也处理有符号整数:

    ("{:0>2X}" * len(x.flatten())).format(*tuple(x.flatten() & (2**8-1)))
    

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多