python - 在python中加载64位原始图像文件

标签 python numpy scipy python-imaging-library

我想知道如何加载this image在Python中。我可以使用图片设置将其加载到 imageJ 中,但我不知道如何在 python 中加载它。

enter image description here

最佳答案

简而言之:

import numpy as np
import matplotlib.pyplot as plt

fname = 'Downloads/image.bdat'
with open(fname, 'r') as infile:
    infile.seek(4)
    data = np.fromfile(infile, dtype='>f8').reshape(1024, 256)

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='gray')
ax.set(xticks=[], yticks=[])
fig.colorbar(im)
fig.savefig('figure_1.png', bbox_inches='tight')
plt.show()

enter image description here


让我备份并解释一下发生了什么。

首先,要将文件中的“原始”数据读入 numpy 数组,请使用 numpy.fromfile使用适当的 dtype,然后 reshape 它。

您拥有我们需要的大部分信息(形状、数据开始的文件偏移量和数据类型)。然而,我们还需要知道其他一些事情:数据的字节顺序和数组的顺序(通常是 C 或 F 顺序)。

numpy.fromfile 的偏移量读取数据,最简单的是seek在调用该函数之前到该偏移量。在您的情况下,在数据开始之前,您在文件中偏移了 4 个字节(大概前 4 个字节是图像大小/形状或其他内容)。

这给了我们:

fname = 'Downloads/image.bdat'
with open(fname, 'r') as infile:
    infile.seek(4)

接下来我们使用fromfile 。然而,您可能尝试的第一件事可能会产生奇怪的结果:

fname = 'Downloads/image.bdat'
with open(fname, 'r') as infile:
    infile.seek(4)
    data = np.fromfile(infile, dtype=np.float64).reshape(1024, 256)

enter image description here

这些值看起来不合理,而且我们在图像中得到了噪声。我们可能使用了错误的数据类型。根据您的信息,我们知道它是某种 64 位 float ,因此最可能的情况是 endianness 中的差异。 。如今,大多数系统都是小端字节序,但许多文件格式出于各种原因而使用大端字节序。在 numpy 中,您可以通过切换到数据类型的字符串规范并使用 > 来指定大端数据类型。表示大端字节序。 (< 表示小端字节序,= 指定使用 native 字节顺序)

这让我们完成了剩下的事情:

fname = 'Downloads/image.bdat'
with open(fname, 'r') as infile:
    infile.seek(4)
    data = np.fromfile(infile, dtype='>f8').reshape(1024, 256)

请注意,我们也可以使用 byteswap方法,如果您发现它更具可读性:

fname = 'Downloads/image.bdat'
with open(fname, 'r') as infile:
    infile.seek(4)
    data = np.fromfile(infile, dtype=np.float64).reshape(1024, 256)
    data = data.byteswap()

我们通常需要最后一条信息:ordering of the array 。对于 2D 数组,只有 C 和 Fortran 排序。对于高维数组,技术上还有其他排序,但几乎从未使用过。

在本例中,它是 C 顺序的(或“行优先”),因此可能的第一个猜测 ( .reshape(nrows, ncols) ) 可以正确工作。如果它是 Fortran 排序的,我们会交换 reshape 中的数字或行和列,然后转置它。

fname = 'Downloads/image.bdat'
with open(fname, 'r') as infile:
    infile.seek(4)
    data = np.fromfile(infile, dtype='>f8').reshape(256, 1024).T

或者,为了更好的可读性,您可以这样做:

data = np.fromfile(infile, dtype='>f8').reshape(1024, 256, order='F')

关于python - 在python中加载64位原始图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356962/

相关文章:

python - FutureWarning : elementwise comparison failed; returning scalar, 但将来会执行元素比较

python - 需要有关 RNN 模型格式化字符串的建议

python - 将列表列转换为二维 numpy 数组

python - 使用 numpy 从边缘列表中累积 "neigborhood"的值

numpy - 将 numpy 数组运算符保留在 np.float32 中

python - 在 scipy.optimize 中恢复优化?

python - pip 未安装 Scrapy 命令行工具

python - 如何在 Django 管理中使用 HTML5 颜色选择器

python - 双三次插值 Python

python - AffinityPropagation 聚类的输入格式