python处理二进制文件_在python中显示二进制文件中的数据

1586010002-jmsa.png

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 is quite handy for reading in simple binary file formats.

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.

Here's a basic idea of what the code would look like:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值