Python Matplotlib Tutorial

Matplotlib imshow – Read & Show image using imread() & plt.imshow()

If you worry about, how to read and show an image using the matplotlib library then here you will get a solution for your problem. Along with that, you will be got a bonus. The matplotlib imshow() function helps to show the image.

But plt.imshow() didn’t work without mpimg.imread() function which is belongs to matplotlib.image module. So lets start practical.

Import Libraries

import matplotlib.pyplot as plt
import matplotlib.image as mpimg # image module for image reading

Reading Image

Here, we use mpimg.imread() method. Which belongs to the matplotlib image module.

img = mpimg.imread("pie_char.png") # give addres of image location
print(img)

Output >>>

[[[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       ...,

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]]], dtype=float32)

Above you can see, when we call img then got numpy array but how. because mpimg.imread() function read pie_char.png image and store in numpy array format.

Get more information about img.

print("Data type of img > ", type(img))
print("Shape of img > ", img.shape)
print("Dimention of img > ",img.ndim)

output >>>

Data type of img > numpy.ndarray

Shape of img > (288, 432, 4)

Dimention of img > 3

Show Image using matplotlib imshow

It’s time to show an image using a read dataset.

To show an image, use plt.imshow() function.

Syntax :plt.imshow(
                                     X,                                     
                                     cmap=None,
                                     norm=None,
                                     aspect=None,
                                     interpolation=None,
                                     alpha=None,
                                     vmin=None,
                                     vmax=None,
                                     origin=None,
                                     extent=None,
                                     shape=None,
                                     filternorm=1,
                                     filterrad=4.0,
                                     imlim=None,
                                     resample=None,
                                     url=None,
                                     *,
                                     data=None,
                                     **kwargs,
                                     )

plt.imshow(img)
plt.show()

Output >>>

Now, removing the axis and increase figure size and then show the same image.

plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(img)
plt.show()

Output >>>

Now, it looks great but can we add it’s a color bar. Yes, using plt.colorbar() function.

Show Image with Colorbar

plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(img)
plt.colorbar() # Show color bar of above image
plt.show()

Output >>>

matplotlib imshow - pi_chart with color

Show Image with cmap Parameter

Let’s play with plt.imshow() functions parameter. Here use cmap means color map to show a single-channel image in a different color.

single_channel = img[:,:,1] # get single channel data from img
plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(single_channel, cmap = "hot") # show image with hot color map
plt.colorbar()
plt.show()

Output >>>

If you want to show an image using a folder path, then follow the below code.

img2 = mpimg.imread("D:\\Private\\Wallpapers\\Pixels\\automobile-beautiful-car-1226458.jpg")
plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(img2)
plt.colorbar()
plt.show()

Output >>>

matplotlib-imshow-model

If, you don’t want to show color bar then remove 5’th no line.

Model image shows with hot color maps (cmap).

single_channel2_img = img2[:,:,1]
plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(single_channel2_img, cmap="hot")
plt.colorbar()
plt.savefig("model_hot.png")
plt.show()
matplotlib imshow - model with hot cmap

Model image shows with nipy_spectral color maps (cmap).

matplotlib imshow - model with nipy_spectral

If we will generate an image with all cmaps then it takes more time. So for that follow the below code.

Below code get cmaps name as a string and split all cmap name as a single item of a list cmap_name_list

cmap = """Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r"""

cmap_name_list = cmap.split(sep = ", ")

Output >>>

['Accent',
 'Accent_r',
 'Blues',
 .
 .
 .
 'viridis_r',
 'winter',
 'winter_r']

Using cmap name create a unique address to store or save generated image in a folder.

save_image_addr_name = []
for i in range(len(cmap_name_list)):
    cmap_str = cmap_name_list[i]
    save_image_addr_name.append("D:\\\cmap_image\\\_"+"girl_" + cmap_name_list[i] + ".png")
    print(save_image_addr_name[i])

Output >>>

D:\\cmap_image\\_girl_Accent.png
D:\\cmap_image\\_girl_Accent_r.png
D:\\cmap_image\\_girl_Blues.png
D:\\cmap_image\\_girl_Blues_r.png
D:\\cmap_image\\_girl_BrBG.png
D:\\cmap_image\\_girl_BrBG_r.png
D:\\cmap_image\\_girl_BuGn.png
D:\\cmap_image\\_girl_BuGn_r.png
D:\\cmap_image\\_girl_BuPu.png
.
.
.
.
.
D:\\cmap_image\\_girl_twilight.png
D:\\cmap_image\\_girl_twilight_r.png
D:\\cmap_image\\_girl_twilight_shifted.png
D:\\cmap_image\\_girl_twilight_shifted_r.png
D:\\cmap_image\\_girl_viridis.png
D:\\cmap_image\\_girl_viridis_r.png
D:\\cmap_image\\_girl_winter.png
D:\\cmap_image\\_girl_winter_r.png

Using cmap_name_list and save_image_addr_name generate cmap image and save it define location with unique address.

for i in range(len(cmap_name_list)): 
    cmap_name = cmap_name_list[i]
    plt.figure(figsize=(16,9))
    plt.axis("off")
    
    print(cmap_name)

    plt.imshow(single_channel2_img, cmap=cmap_name)
    #plt.colorbar()
    #save_image_name1 = "D:\\cmap_image\\"+"girl" + cmap_list[i]
    print(save_image_addr_name[i])
    plt.savefig(save_image_addr_name[i], orientation='portrate', facecolor= "k")
    plt.show()

Output >>>

matplotlib imshow - model with all cmap values

Conclusion

In the matplotlib imshow blog, we learn how to read, show image and colorbar with a real-time example using the mpimg.imread, plt.imshow() and plt.colorbar() function. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib imshow source code

Visit the official site of matplotlib.org

Leave a Reply