【问题标题】:Displaying data from binary file in python在python中显示二进制文件中的数据
【发布时间】:2013-11-27 15:21:52
【问题描述】:

我有 2000 张图像存储为单个二进制文件“file.dat”和该文件的 512 字节头。每个图像的格式为 512*512*2 字节(无符号整数 16)。我的任务是将所有这些图像可视化为视频。我怎样才能在python中做到这一点?我的问题是从阅读图像序列开始。我是python的新手。

【问题讨论】:

  • python 有 opencv 绑定。我会从那里开始

标签: python python-3.x numpy matplotlib


【解决方案1】:

Numpy 对于读取简单的二进制文件格式非常方便。

从它的声音来看,您有一个大的 uin16 二进制文件,您希望将其读入 3D 数组并进行可视化。我们不必将其全部加载到内存中,但对于本示例,我们将。

以下是代码外观的基本概念:

import numpy as np
import matplotlib.pyplot as plt

def main():
    data = read_data('test.dat', 512, 512)
    visualize(data)

def read_data(filename, width, height):
    with open(filename, 'r') as infile:
        # Skip the header
        infile.seek(512)
        data = np.fromfile(infile, dtype=np.uint16)
    # Reshape the data into a 3D array. (-1 is a placeholder for however many
    # images are in the file... E.g. 2000)
    return data.reshape((width, height, -1))

def visualize(data):
    # There are better ways to do this, but let's keep it simple
    plt.ion()
    fig, ax = plt.subplots()
    im = ax.imshow(data[:,:,0], cmap=plt.cm.gray)
    for i in xrange(data.shape[-1]):
        image = data[:,:,i]
        im.set(data=image, clim=[image.min(), image.max()])
        fig.canvas.draw()

main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-29
    • 2014-02-20
    • 2014-11-27
    • 2012-09-30
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多