Matplotlib Example | Clip and Display an Image with Patches

In this matplotlib example, we will introduce how to clip and display and image with patches.

Step 1: load an image in matplotlib

For example:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cbook as cbook


with cbook.get_sample_data('img.jpg') as image_file:
    image = plt.imread(image_file)

Step 2: display an image

fig, ax = plt.subplots()
im = ax.imshow(image)

In this example, we use ax.imshow() to display an image in matplotlib.

Step 3: clip this image

For example:

patch = patches.Circle((100, 100), radius=90, transform=ax.transData)
im.set_clip_path(patch)

ax.axis('off')
plt.show()

In this example code, we have used im.set_clip_path() to clip an image with patch.

Finally, we can find an image like this:

Matplotlib Example | Clip and Display an Image with Patches