Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read in Raw Binary Image in Python

I have a very simple script in Matlab that opens a 'raw' binary image file and displays it. Is this easily reproducible using numpy in python? I've come across various posts discussing unpacking, dealing with endian, specifying buffers, etc. But this seems like it should be simple, based on how simple the matlab interface is

>> fileID = fopen('sampleX3.raw','rb')

fileID =

     1

>> A = fread(fileID,[1024,1024],'int16');
size(A)

ans =

        1024        1024

>> max(max(A))

ans =

       12345

>> close all; figure; imagesc(A);
like image 395
Joe Avatar asked Jul 04 '13 23:07

Joe


People also ask

How do I read a binary image in Python?

fromfile("c:\temp\Binary_File. jpg", dtype=dt) df = pd. DataFrame(data) print(df) except IOError: print("Error while opening the file!") This is how you can read a binary file using NumPy and use that NumPy array to create the pandas dataframe.

How do I read a binary file in Python?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.


1 Answers

This will do the same thing using numpy and matplotlib:

import numpy as np
from matplotlib import pylab as plt

A = np.fromfile(filename, dtype='int16', sep="")
A = A.reshape([1024, 1024])
plt.imshow(A)

I feel obligated to mention that using raw binary files to store data is generally a bad idea.

like image 86
Bi Rico Avatar answered Nov 15 '22 01:11

Bi Rico