python - 从 Python 编写真正的原始二进制文件

标签 python python-3.x numpy binary

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

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

最佳答案

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())

关于python - 从 Python 编写真正的原始二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54998630/

相关文章:

python - numpy.fft.fft 中参数 n 的影响是什么

python - 是否可以将范围作为变量 "var = k:k+number"

python - Factory 和 ServerFactory/ClientFactory 有什么区别?

python - 执行练习代码时,即使在 datetime 模块之后也会出现错误

image - 使用 python urllib 从 url 下载图像但收到 HTTP 错误 403 : Forbidden

使用ctypes将python字符串对象转换为c char *

python - Numpy 列和行向量

python - 为什么 tkinter.filedialog.askdirectory 不返回完整路径(带有选定的目录名)?

python - 在缺少的模块上构建 Python 等

python - 如何降级openssl