Note
Click here to download the full example code
Image antialiasing¶
Images are represented by discrete pixels, either on the screen or in an image file. When data that makes up the image has a different resolution than its representation on the screen we will see aliasing effects.
The default image interpolation in Matplotlib is 'antialiased'. This uses a hanning interpolation for reduced aliasing in most situations. Only when there is upsampling by a factor of 1, 2 or >=3 is 'nearest' neighbor interpolation used.
Other anti-aliasing filters can be specified in Axes.imshow
using the
interpolation keyword argument.
import numpy as np
import matplotlib.pyplot as plt
First we generate a 500x500 px image with varying frequency content:
The following images are subsampled from 500 data pixels to 303 rendered pixels. The Moire patterns in the 'nearest' interpolation are caused by the high-frequency data being subsampled. The 'antialiased' image still has some Moire patterns as well, but they are greatly reduced.
![interpolation='nearest', interpolation='antialiased'](../../_images/sphx_glr_image_antialiasing_001.png)
Even up-sampling an image with 'nearest' interpolation will lead to Moire patterns when the upsampling factor is not integer. The following image upsamples 500 data pixels to 530 rendered pixels. You may note a grid of 30 line-like artifacts which stem from the 524 - 500 = 24 extra pixels that had to be made up. Since interpolation is 'nearest' they are the same as a neighboring line of pixels and thus stretch the image locally so that it looks distorted.
fig, ax = plt.subplots(figsize=(6.8, 6.8))
ax.imshow(a, interpolation='nearest', cmap='gray')
ax.set_title("upsampled by factor a 1.048, interpolation='nearest'")
plt.show()
![upsampled by factor a 1.048, interpolation='nearest'](../../_images/sphx_glr_image_antialiasing_002.png)
Better antialiasing algorithms can reduce this effect:
fig, ax = plt.subplots(figsize=(6.8, 6.8))
ax.imshow(a, interpolation='antialiased', cmap='gray')
ax.set_title("upsampled by factor a 1.048, interpolation='antialiased'")
plt.show()
![upsampled by factor a 1.048, interpolation='antialiased'](../../_images/sphx_glr_image_antialiasing_003.png)
Apart from the default 'hanning' antialiasing imshow
supports a
number of different interpolation algorithms, which may work better or
worse depending on the pattern.
![interpolation='hanning', interpolation='lanczos'](../../_images/sphx_glr_image_antialiasing_004.png)
References¶
The use of the following functions and methods is shown in this example:
import matplotlib
matplotlib.axes.Axes.imshow
Out:
<function Axes.imshow at 0x7f280feb3310>
Total running time of the script: ( 0 minutes 1.484 seconds)
Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery