How To Display Image In Python

Displaying images is a core feature in many applications, including image processing tools, photo galleries, and games. In this tutorial, we’ll explore how to display an image using Python, leveraging the powerful Python Imaging Library (PIL), which is now maintained as Pillow.

Step 1: Install the Pillow Library

To work with images in Python, first we need to install the Pillow library. You can install Pillow using pip by running the following command in your terminal:

Step 2: Load an Image

Now that our environment is set up, let’s load an image. To load an image, we’ll use the Image.open() method from the PIL module. Replace the “sample_image.jpg” with the path to your image.

Step 3: Display the Image

With the image loaded, displaying it is as simple as calling the show() method. This will open the image with the default image viewer on your system.

Step 4: Display the Image using the Tkinter Library (Optional)

An alternative method to display images in Python is to use the popular Tkinter library, which comes pre-installed with Python. This is especially useful when you want to create a custom GUI to handle image processing and other functionalities.

First, we will need to import the Tkinter and ImageTk modules. Next, we’ll create a simple display_image function that incorporates Tkinter’s functionalities to display the image.

To test the display_image function, just call it and provide the image path as an argument:

Full Code

Conclusion

In this tutorial, we demonstrated how to display images in Python using the Python Imaging Library (PIL, now maintained as Pillow) and the Tkinter library. These libraries provide functionalities for loading, displaying, and manipulating images in various ways, and are powerful tools for developers working on image-based applications.