0

Matlab Code:

binary = 'binaryfile.png';
fid = fopen(binary , 'rb'); 
data2d(:,:) = fread(fid, [10,10], ['int16=>','double'])

I am looking for Python equivalent of above code. I can use numpy.fromfile function to read but it doesn't allows me to read in two dimension. Any help or idea how can one do this in Python.

2 Answers 2

2

Although it is possible to do what you want, you wouldn't do this in Python because you don't need to. What you want to do this:

binary = 'binaryfile.png'
data2d = np.fromfile(binary, count=10*10, dtype='int16').reshape(10, 10).astype('double')

reshape in numpy takes essentially no time and no extra memory, unlike MATLAB where it is an expensive operation. This is because in numpy reshape doesn't copy the data like it does in MATLAB, it is just a different way of looking at the same underlying data.

So in numpy, this is the best way to do what you want to do. The MATLAB functionality you are looking for is really a workaround for limitations in the MATLAB language. numpy doesn't have those limitations, allowing for a simpler function. Generally it is considered good programming practice to split tasks into a series of simple, well-defined operations rather than put everything in a single function. But due to limitations in the language, this tends to be a lot harder in MATLAB than in python, resulting in MATLAB generally having much more complicated functions.

Now, as I said, it is possible to do what you want, but it is uglier and harder to read without any real advantage so I strongly advise you to use the above approach. But here is how you would to the same thing in numpy:

binary = 'binaryfile.png'
data2d = np.fromfile('binaryfile.png', count=10, dtype=('int16', 10)).astype('double')

This is basically telling it to read in a length-10 int16 row 10 times. Interestingly, at least in my tests, this approach is actually slower than the first approach I described, probably due to the more complexity when doing the reading. Reading files from disk is always slow, so anything that makes it more complex will hurt performance.

Sign up to request clarification or add additional context in comments.

Comments

0
binary = 'binaryfile.png';
fid = open(binary , 'rb'); 
data1d = numpy.fromfile(fid, count = 10*10, dtype = numpy.int16)
data2d = numpy.double(data1d.reshape(10,10))

I somehow managed to do it in otherway. But it will be still nice to know if there is something as same in matlab.....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.