2013-11-27 57 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()