2013-11-27 27 views
1

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

+1

Python有OpenCV的绑定。我会从那里开始 – Hammer

回答

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