Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine the phase of one image and magnitude of different image into 1 image by using python

I want to combine phase spectrum of one image and magnitude spectrum of different image into one image.

I have got phase spectrum and magnitude spectrum of image A and image B.

Here is the code.

f = np.fft.fft2(grayA)
fshift1 = np.fft.fftshift(f)
phase_spectrumA = np.angle(fshift1)
magnitude_spectrumB = 20*np.log(np.abs(fshift1))

f2 = np.fft.fft2(grayB)
fshift2 = np.fft.fftshift(f2)
phase_spectrumB = np.angle(fshift2)
magnitude_spectrumB = 20*np.log(np.abs(fshift2))

I trying to figure out , but still i do not know how to do that.

Below is my test code.

imgCombined = abs(f) * math.exp(1j*np.angle(f2))

I wish i can come out just like that

enter image description here

like image 806
DENG LI Avatar asked Sep 13 '18 10:09

DENG LI


1 Answers

Here are the few things that you would need to fix for your code to work as intended:

  • The math.exp function supports scalar exponentiation. For an element-wise matrix exponentiation you should use numpy.exp instead.
  • Similary, the * operator would attempt to perform matrix multiplication. In your case you want to instead perform element-wise multiplication which can be done with np.multiply

With these fixes you should get the frequency-domain combined matrix as follows:

combined = np.multiply(np.abs(f), np.exp(1j*np.angle(f2)))

To obtain the corresponding spatial-domain image, you would then need compute the inverse transform (and take the real part since there my be residual small imaginary parts due to numerical errors) with:

imgCombined = np.real(np.fft.ifft2(combined))

Finally the result can be shown with:

import matplotlib.pyplot as plt
plt.imshow(imgCombined, cmap='gray')

enter image description here

Note that imgCombined may contain values outside the [0,1] range. You would then need to decide how you want to rescale the values to fit the expected [0,1] range.

  • The default scaling (resulting in the image shown above) is to linearly scale the values such that the minimum value is set to 0, and the maximum value is set to 0.
  • Another way could be to limit the values to that range (i.e. forcing all negative values to 0 and all values greater than 1 to 1).
  • Finally another approach, which seems to provide a result closer to the screenshot provided, would be to take the absolute value with imgCombined = np.abs(imgCombined)

enter image description here

like image 118
SleuthEye Avatar answered Nov 14 '22 10:11

SleuthEye