我有一个二进制文件格式.dat。我想将其转换为 png 或 jpg 格式,我尝试使用 numpy.loadtxt() 对其进行解码以获取数组列表,然后将其保存为 png 或 jpg 格式。但是当我执行它时,它给出了错误
File "C:\Users\SETIKO\Desktop\test\test6-savedattopng.py", line 13, in arr = np.loadtxt(f)
File "C:\Users\SETIKO\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py", line 1101, in loadtxt for x in read_data(_loadtxt_chunksize):
File "C:\Users\SETIKO\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py", line 1028, in read_data items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Users\SETIKO\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py", line 1028, in items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Users\SETIKO\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py", line 746, in floatconv return float(x)
这是我使用的完整代码
import numpy as np
f = open('gt.dat', 'rb')
arr = np.loadtxt(f)
我的代码中是否缺少某些内容?或者也许有人有其他想法而无需使用 numpy.loadtxt() ?
这是我使用的二进制文件: Binary dat file
最佳答案
最简单的是,您可以读取文件并将其制作为 PIL/Pillow 图像,如下所示:
import numpy as np
from PIL import Image
# Read file into Numpy array as uint8
na = np.fromfile('GT.dat', dtype=np.uint8)
# Reshape to 5292 px wide, 744 px tall and RGBA, i.e. 4 bytes/per pixel
na = np.reshape(na,(744,5292,4))
# Drop the alpha channel, retaining just RGB
na = na[:,:,:3]
# Convert to PIL/Pillow Image - whilst also brightening because values are all <=5
im = Image.fromarray(na*50,'RGB')
# Save
im.save('result.png')
<小时/>
或者您根本不需要编写任何代码,只需使用大多数 Linux 发行版中包含的 ImageMagick 即可,并且适用于 macOS 和 Windows。所以,就在终端中:
convert -depth 8 -size 5292x744 rgba:GT.dat -normalize result.png
<小时/>
更新答案
看起来所有数据实际上都在红色 channel 中,而绿色、蓝色或Alpha channel 中没有任何数据。因此,我们将丢弃这些,然后,由于红色 channel 中的值都是小整数,我们将创建一个调色板图像,其中这些整数是我们可以轻松操作的调色板的索引。
#!/usr/bin/env python3
import numpy as np
from PIL import Image
# Read file into Numpy array as uint8
na = np.fromfile('GT.dat', dtype=np.uint8)
# Reshape to 5292 px wide, 744 px tall and RGBA, i.e. 4 bytes/per pixel
na = np.reshape(na,(744,5292,4))
# Construct a palette
palette = [
0, 0, 0, # 0 - black
255, 0, 0, # 1 - red
0, 255, 0, # 2 - green
0, 0, 255 # 3 - blue
]
# There must be exactly 256 RGB colours, so pad palette to length 768 with zeroes
palette += (768-len(palette))*[0]
# Drop everything except the Red channel which contains all the data
na = na[:,:,0]
# Convert to single channel PIL/Pillow Image
im = Image.fromarray(na,'L')
# Put our palette into image
im.putpalette(palette)
# Save
im.save('result.png')
关于python - 如何将二进制 dat 文件 (.dat) 保存为 png 或 jpg 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56524458/