我尝试了多种不同的变体,但由于某种原因,我不断地将无效的二进制数字(人类可读的)输出到文件中:
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'
我该如何解决这个问题?
任何帮助将不胜感激。
我尝试过的其他解决方案:
最佳答案
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/