Imshow Tutorial in Matplotlib

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

12 import matplotlib.pyplot as pltimport matplotlib.image as mpimg # image module for image reading

Reading Image

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

12 img = mpimg.imread("pie_char.png") # give addres of image locationprint(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.

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

output >>>

12345 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.

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

Output >>>

Imshow Tutorial in Matplotlib 1

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

Show Image with Colorbar

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

Output >>>

Imshow Tutorial in Matplotlib 2

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.

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

Output >>>

Imshow Tutorial in Matplotlib 3

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

123456 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 >>>

Imshow Tutorial in Matplotlib 4

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

Model image shows with hot color maps (cmap).

1234567 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()
Imshow Tutorial in Matplotlib 5

Model image shows with nipy_spectral color maps (cmap).

Imshow Tutorial in Matplotlib 6

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

123 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 >>>

123456789 ['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.

12345 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 >>>

Output >>>

12345678910111213141516171819202122 D:\\cmap_image\\_girl_Accent.pngD:\\cmap_image\\_girl_Accent_r.pngD:\\cmap_image\\_girl_Blues.pngD:\\cmap_image\\_girl_Blues_r.pngD:\\cmap_image\\_girl_BrBG.pngD:\\cmap_image\\_girl_BrBG_r.pngD:\\cmap_image\\_girl_BuGn.pngD:\\cmap_image\\_girl_BuGn_r.pngD:\\cmap_image\\_girl_BuPu.png.....D:\\cmap_image\\_girl_twilight.pngD:\\cmap_image\\_girl_twilight_r.pngD:\\cmap_image\\_girl_twilight_shifted.pngD:\\cmap_image\\_girl_twilight_shifted_r.pngD:\\cmap_image\\_girl_viridis.pngD:\\cmap_image\\_girl_viridis_r.pngD:\\cmap_image\\_girl_winter.pngD:\\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.

12345678910111213 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 >>>

Imshow Tutorial in Matplotlib 7

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.

This article has been published from the source link feed without modifications to the text. Only the headline has been changed.

Source link

Most Popular