Skip to content Skip to sidebar Skip to footer

Altered Image Array When Plotting With Pyplot's Imshow

So i noticed for me and a few of my colleagues that when we display a binary array using matplotlib.pyplot's imshow function the edges of the displayed image seems altered. For a w

Solution 1:

imshow doesn't know about your data being discrete or even binary. Default it adds some interpolation. You can suppress the smooth interpolation using imshow(...., interpolation='none') (or interpolation='nearest').

Note that the default mode is 'antialiased' for which the effect is different depending on the number of screen pixels occupied by an image pixel. See the official matplotlib documentation for more details.

Here is some test code comparing the default and the 'none' interpolation mode for different image sizes:

from matplotlib import pyplot as plt
import numpy as np

x = np.round(10 + np.random.uniform(-.1, .1, (100, 100)).cumsum(axis=0).cumsum(axis=1))
x[x % 2 == 0] = x.max() + 1
fig, axes = plt.subplots(2, 6, figsize=(14, 5))
for i, axrow inenumerate(axes):
    for j, ax inenumerate(axrow):
        k = 10 * (j + 5)
        ax.imshow(x[-k:, -k:], cmap='Dark2', interpolation=Noneif i == 0else'none')
        ax.set_title("size={}\ninterpolation={}".format(k, 'None'if i == 0else"'none'"))
plt.tight_layout()
plt.show()

comparison

Here is another example, using the 'seismic' colormap and only two data values. This colormap has dark blue and red at the extremes and white near the center, which shows the interpolation much more pronunciated:

two data values, seismic cmap

Post a Comment for "Altered Image Array When Plotting With Pyplot's Imshow"