Python | Working with PNG images with Matplotlib

Python Methods and Functions

In this article, we will see how we can work with PNG images using Matplotlib.

Code # 1: Reading PNG images using Matplotlib

# import pyplot and images from matplotlib

import matplotlib.pyplot as plt

import matplotlib.image as img

 
# read the png image file

im = img.imread ( 'imR. png' )

 
# show image
plt.imshow (im)

Output:

Code # 2: Applying a mock color to an image

A pseudo color is useful for increasing the contrast of an image.

# import pyplot and images from matplotlib

import matplotlib.pyplot as plt

import matplotlib.image as img

 
# read png image

im = img.imread ( ' imR.png' )

 
# apply a pseudo color
# use the default colormap.

lum = im [:,:, 0 ]

 
# show image
plt.imshow (lum)

Output:

Code # 3: We can provide a different meaning to the colormap using colorbar.

# import pyplot and images from matplotlib

import matplotlib.pyplot as plt

import matplotlib.image as img

  
# read png image

im = img.imread ( 'imR.png' )

lum = im [:,:, 0 ]

 
# set the colormap as hot

plt.imshow (lum, cmap = 'hot' )

plt.colorbar ( )

Output:

Interpolation Schemes:
Interpolation calculates what color or pixel value should be, and this is necessary when we resize an image but want the same information. There is not enough space when resizing the image because the pixels are discrete and interpolation — this is how you fill that space.

Code # 4: interpolation

# PIL import and matplotlib

from PIL import Image 

import matplotlib.pyplot as plt

 
# read the png image file

img = Image. open ( 'imR.png' )

 
# resize the image

img.thumbnail (( 50 , 50 ), Image. ANTIALIAS)

imgplot = plt.imshow (img)

Output:

Code # 6: Here, "bicubic" is used for bipolation value.

# import pyplot from matplotlib

import matplotlib.pyplot as plt

 
# import images from PIL

from PIL import Image 

 
# read image

img = Image. open ( 'imR.png' )

 

img.thumbnail (( 30 , 30 ), Image.ANTIALIAS) 

 
# bicubic used for interpolation

imgplot = plt.imshow (img, interpolation = 'bicubic' )

Output:

Code # 7: value & # 39; sinc & # 39; used for interpolation.

# PIL and matplotlib imports

from PIL import Image 

import matplotlib.pyplot as plt

 
# read image

img = Image. open ( 'imR. png' )

 

img.thumbnail (( 30 , 30 ), Image.ANTIALIAS)

< p>  
# sinc is used for interpolation

imgplot = plt.imshow (img, interpolation = 'sinc' )

Output:

Link: https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html





Get Solution for free from DataCamp guru