Search code examples
pythonimagematlabgrayscale

Producing equal images in Python and Matlab - How to?


I am working on a project that involves both Matlab and Python and I am producing some images. Altough the matrixes I want to transform into images are the same, the images I get are not the same. I assume this has something to do with the equivalence between Python and Matlab commands for displaying images and thus this is why I am here.

MATLAB CODE:

fmn0 = imread('cameraman.tif');
fmn=double(ifftshift(fmn0,2));
Fun=fftshift(fft(fmn,[],2),2); 

imshow(real(Fun))

MATLAB OUTPUT:

enter image description here

PYTHON CODE:

import numpy as np
import matplotlib.pyplot as plt
import cv2

def row_wise_fft(A):
    A = np.asarray(A)
    rowWiseFFT = np.zeros((A.shape[0], A.shape[1]), dtype='complex')
    for i in range(0, A.shape[0]):
        rowWiseFFT[i, :] = np.fft.fft(A[i,:])
    return rowWiseFFT

def row_wise_ifftshift(A):
    for i in range(0, len(A)):
        A[i] = np.fft.ifftshift(A[i])
    return A

def row_wise_fftshift(A):
    for i in range(0, len(A)):
        A[i] = np.fft.fftshift(A[i])
    return A

fmn = cv2.imread("cameraman.tif", cv2.IMREAD_GRAYSCALE)

fun = row_wise_fftshift(row_wise_fft(row_wise_ifftshift(fmn)))

plt.set_cmap("Greys_r")
plt.imshow(fun.real)

PYHTON OUTPUT:

enter image description here

I can see some similarities, but how would one leave the Python output as the exact same as the Matlab one? Note that the fun matrixes are the exact same.


Solution

  • MATLAB autoscales the output to [0 1], so most of your data in the MATLAB plot is extremely saturated and not really visible.

    do imshow(real(Fun),[]) to remove the saturation and actually see all your data (MATLAB).

    do plt.clim([0,1]) to saturate the visualization of your data in python.

    You can also just give either MATLAB or python a different range of values to visualize (e.g. [0, 15])