In this section, we'll explore how to load and display images using two popular Python libraries: Matplotlib and PIL (Pillow).

1. Installing Required Libraries

First, ensure that you have the necessary libraries installed. You can install them using pip if they aren't already installed:

%pip install numpy matplotlib pillow

2. Importing Libraries

Before you start writing your image handling code, you'll need to import the necessary modules:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

3. Loading and Displaying Images with PIL

Pillow (PIL Fork) is a powerful library that supports opening, manipulating, and saving many different image file formats.

Loading an Image

# Load an image from file
image_path = '<https://upload.wikimedia.org/wikipedia/en/thumb/7/7d/Lenna_%28test_image%29.png/330px-Lenna_%28test_image%29.png>'
img = Image.open(image_path)

Displaying the Image

# Display the image using PIL's own display method
img.show()

4. Converting Images for Use with Matplotlib

While you can display images directly with PIL, Matplotlib provides more flexibility for displaying images within a graphical context, such as alongside graphs or as part of a larger visualization.

Convert PIL Image to NumPy Array

# Convert to NumPy array
img_np = np.array(img)

Checking the Shape of the Image

print("Shape of the image:", img_np.shape)

Displaying with Matplotlib