Matplotlib Image Thumbnail

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab will guide you through the process of generating thumbnails from existing images using Matplotlib library in Python. Thumbnails are smaller versions of images that can be used to display a preview of the larger image. Matplotlib depends on Pillow library for reading images and supports all formats supported by Pillow.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/booleans -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/conditional_statements -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/for_loops -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/tuples -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/sets -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/importing_modules -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/using_packages -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/standard_libraries -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/os_system -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/data_visualization -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} python/build_in_functions -.-> lab-48783{{"`Matplotlib Image Thumbnail`"}} end

Install Required Libraries

First, you need to install the required libraries. Open your terminal and type the following commands to install Matplotlib and Pillow:

pip install matplotlib
pip install pillow

Import Libraries

In this step, you will import the libraries you installed in the previous step. You need to import ArgumentParser and Path from argparse and pathlib modules respectively. Also, import sys and image modules from sys and matplotlib.image modules respectively.

from argparse import ArgumentParser
from pathlib import Path
import sys
import matplotlib.image as image

Parse Arguments

In this step, you will parse the arguments passed to your program. You need to create an ArgumentParser object and add an argument named imagedir. This argument specifies the path to the directory containing the images. You can use the type parameter to specify the data type of the argument. In this case, the argument should be of type Path.

parser = ArgumentParser(description="Build thumbnails of all images in a directory.")
parser.add_argument("imagedir", type=Path)
args = parser.parse_args()

Verify Directory

In this step, you will check if the specified directory exists. If the directory does not exist, you will exit the program and print an error message.

if not args.imagedir.is_dir():
    sys.exit(f"Could not find input directory {args.imagedir}")

Create Output Directory

In this step, you will create a directory named thumbs where the thumbnails will be saved. If the directory already exists, it will not be created again.

outdir = Path("thumbs")
outdir.mkdir(parents=True, exist_ok=True)

Generate Thumbnails

In this step, you will generate thumbnails for all the images in the specified directory. You will use a for loop to iterate over all the images with the .png extension in the specified directory. For each image, you will generate a thumbnail and save it in the thumbs directory.

for path in args.imagedir.glob("*.png"):
    outpath = outdir / path.name
    fig = image.thumbnail(path, outpath, scale=0.15)
    print(f"saved thumbnail of {path} to {outpath}")

Summary

In this lab, you have learned how to generate thumbnails from existing images using Matplotlib in Python. You have learned how to import libraries, parse arguments, verify directories, create output directories and generate thumbnails. By following the steps in this lab, you can easily generate thumbnails for all the images in a directory.

Other Python Tutorials you may like