在python中显示二进制文件中的数据 [英] Displaying data from binary file in python

查看:468
本文介绍了在python中显示二进制文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2000个图像存储为单个二进制文件"file.dat",并且该文件的头为512字节.每个图像的格式为512 * 512 * 2字节(无符号int 16).我的任务是将所有这些图像可视化为视频.我该如何在python中做到这一点?我的问题是从读取图像序列开始的.我是python的新手.

I have 2000 images stored as single binary file "file.dat" and a head of 512 bytes to this file. Format of every image is 512*512*2 bytes (unsigned int 16). My task is to visualize all this images as video. How can I do this in python? My problem is starting from reading the sequence of images. I'm newbie in python.

推荐答案

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

Numpy is quite handy for reading in simple binary file formats.

从声音上看,您有一个很大的uin16二进制文件,您想将其读入3D数组并进行可视化处理.我们不必将所有内容都加载到内存中,但是对于此示例,我们将这样做.

From the sound of it, you have a large binary file of uin16's that you want to read into a 3D array and visualize. We don't have to load it all into memory, but for this example, we will.

这是代码的基本概念:

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

这篇关于在python中显示二进制文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆