Python | Working with PNG Images using Matplotlib
Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. Matplotlib consists of several plots like line, bar, scatter, histogram etc. In this article, we will see how to work with PNG images using Matplotlib.
Example 1: Read a PNG image using Matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading png image file
im = img.imread('imR.png')
# show image
plt.imshow(im)
Output

Example 2: Applying pseudocolor to image
Pseudocolor is useful for enhancing contrast of image.
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading png image
im = img.imread('imR.png')
# applying pseudocolor
# default value of colormap is used.
lum = im[:, :, 0]
# show image
plt.imshow(lum)
Output

Example 3: We can provide another value to colormap with colorbar.
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading png image
im = img.imread('imR.png')
lum = im[:, :, 0]
# setting colormap as hot
plt.imshow(lum, cmap ='hot')
plt.colorbar()
Output

Interpolation Schemes
Interpolation calculates what the color or value of a pixel “should” be and this needed when we resize the image but want the same information. There's missing space when you resize image because pixels are discrete and interpolation is how you fill that space.
Example 4: Interpolation
from PIL import Image
import matplotlib.pyplot as plt
# reading png image file
img = Image.open('imR.png')
# resizing the image using updated resampling
img.thumbnail((50, 50), Image.Resampling.LANCZOS)
# display
plt.imshow(img)
Output

Example 5: Here, 'bicubic' value is used for interpolation.
import matplotlib.pyplot as plt
from PIL import Image
# reading image
img = Image.open('imR.png')
# resizing with updated resampling
img.thumbnail((30, 30), Image.Resampling.LANCZOS)
# bicubic used for interpolation while displaying
plt.imshow(img, interpolation='bicubic')
Output

Example 6: 'sinc' value is used for interpolation.
from PIL import Image
import matplotlib.pyplot as plt
# reading image
img = Image.open('imR.png')
# resizing with updated resampling
img.thumbnail((30, 30), Image.Resampling.LANCZOS)
# sinc used for interpolation while displaying
plt.imshow(img, interpolation='sinc')
Output