Drawing circles on image with Matplotlib and NumPy

orkan picture orkan · Jan 20, 2016 · Viewed 32.4k times · Source

I have NumPy arrays which hold circle centers.

import matplotlib.pylab as plt
import numpy as np
npX = np.asarray(X)
npY = np.asarray(Y)
plt.imshow(img)
// TO-DO
plt.show()

How can I show circles at the given positions on my image?

Answer

tmdavison picture tmdavison · Jan 20, 2016

You can do this with the matplotlib.patches.Circle patch.

For your example, we need to loop through the X and Y arrays, and then create a circle patch for each coordinate.

Here's an example placing circles on top of an image (from the matplotlib.cbook)

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle

# Get an example image
import matplotlib.cbook as cbook
image_file = cbook.get_sample_data('grace_hopper.png')
img = plt.imread(image_file)

# Make some example data
x = np.random.rand(5)*img.shape[1]
y = np.random.rand(5)*img.shape[0]

# Create a figure. Equal aspect so circles look circular
fig,ax = plt.subplots(1)
ax.set_aspect('equal')

# Show the image
ax.imshow(img)

# Now, loop through coord arrays, and create a circle at each x,y pair
for xx,yy in zip(x,y):
    circ = Circle((xx,yy),50)
    ax.add_patch(circ)

# Show the image
plt.show()

enter image description here