Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib imshow inverting colors of 2D IFFT array

I have been doing some work deconvoluting images with 2D Scipy FFTs. However, Matplotlib for no apparent reason is inverting the color scheme of the generated IFFT array, even though the RGB values are correct.

import numpy as np
from scipy import fftpack
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = mpimg.imread("C:/Users/-----/Desktop/image.jpg")
freq = fftpack.fft2(image)
IFFT = fftpack.ifft2(freq)
IFFT = IFFT.astype('float32')

plt.figure(1)
plt.imshow(image)

plt.figure(2)
plt.imshow(IFFT)

plt.show()

The IFFT array and image array are equal according to numpy.array_equal, and yet the colormap of the second figure is always inverted. See the attached images. The arrays are literally identical and no other colormap is specified, and yet I am forced to manual invert everything using something like this:

for i in range(0, freq.shape[1]):
    for j in range (0, freq.shape[0]):
        for k in range(0,3):
            freq[j,i,k] = 255-freq[j,i,k]

I wonder if the astype conversion to float32 (or earlier uint32) might be changing something, but since arrays are identical, I have no idea.

Any ideas? I'd also like to figure out how to invert the entire cmap if that would be a more efficient alternative to manually subtracting 255 from every entry in the array.

First image Second image

like image 859
JAustin Avatar asked Jan 22 '26 04:01

JAustin


2 Answers

plt.imshow() expects integers.

However, I noticed that even though two arrays of integers can look identical, they might have different types of integers.

In my case, when looking at integer type in the "right" array (i.e. the one where the colors display properly) I got: class 'numpy.uint8'

Whereas when looking at integer type in the array where the colors are inverted in plt.imshow() I got: class 'numpy.int64'

All I needed to do was to convert the array values to uint8:

image = image.astype(np.uint8)

like image 194
Alexis Saint-Jean Avatar answered Jan 24 '26 17:01

Alexis Saint-Jean


Not at all. You are dealing with numpy arrays and as so you can just:

 freq = 255 - freq

So your code would be:

import numpy as np
from scipy import fftpack
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = mpimg.imread("EGZ68.jpg")
freq = fftpack.fft2(image)
freq = 255 - freq  # HERE IS THE CHANGE
IFFT = fftpack.ifft2(freq)
IFFT = IFFT.astype('float32')

plt.figure(1)
plt.imshow(image)

plt.figure(2)
plt.imshow(IFFT)

plt.show()

Although I'm not sure why you are getting a an inversed colormap in the first place.

like image 29
armatita Avatar answered Jan 24 '26 18:01

armatita