简体   繁体   中英

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.

第一张图片 第二张图片

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 (ie 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM