0
$\begingroup$

When I import an image from Matlab I get the following jumbled image

enter image description here

rather than the (224x224x3 RGB) image of a single elephant I expected

enter image description here

I write the image from Matlab as a binary file

function save_bin(filename, input_image)
  r = input_image(:,:,1); % dump image for input to python
  g = input_image(:,:,2);
  b = input_image(:,:,3);
  fid = fopen(filename,'wb');
  fwrite(fid, r(:), 'float32');
  fwrite(fid, g(:), 'float32');
  fwrite(fid, b(:), 'float32');
  fclose(fid);
endfunction

And read it back into Python as follows

m_resized = np.reshape(np.fromfile('m_resized.bin', dtype=np.float32),(224,224,3))
image = Image.fromarray(np.uint8(m_resized), 'RGB')
image.show()

I've investigated the slicing differences creating a 3x3x3 tensor in Matlab and importing it and there's a fundamental difference in the slicing syntax between Matlab Python but this alone doesn't explain what's going wrong

Any ideas?

Note: The reason I'm using a binary format rather than a jpg image is that I want to compare a Matlab CNN model to a Numpy implementation at each stage and using an image is an intelligible means of comparison rather than comparing lots of numbers.

$\endgroup$
1
$\begingroup$

The answer is that the order in which pixels are accessed in Matlab is different from that in Python

The problem is resolved by specifying the order in the numpy reshape function to be the same as that of Matlab using the order='F' flag

Where ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest

def display_image(input_image) :
  image = Image.fromarray(np.uint8(input_image), 'RGB')
  image.show()

m_resized = np.reshape(np.fromfile('../resnet50_matlab/m_resized.bin', dtype=np.float32),(224,224,3), order='F')

display_image(m_resized)

This results in the correct image being displayed as shown in the image below

enter image description here

Rather than the mangled image displayed using

m_mangled = np.reshape(np.fromfile('../resnet50_matlab/m_resized.bin', dtype=np.float32),(224,224,3))

display_image(m_mangled)

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.