Drawing circles on image with Matplotlib and NumPy Drawing circles on image with Matplotlib and NumPy python python

Drawing circles on image with Matplotlib and NumPy


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 pltimport numpy as npfrom matplotlib.patches import Circle# Get an example imageimport matplotlib.cbook as cbookimage_file = cbook.get_sample_data('grace_hopper.png')img = plt.imread(image_file)# Make some example datax = np.random.rand(5)*img.shape[1]y = np.random.rand(5)*img.shape[0]# Create a figure. Equal aspect so circles look circularfig,ax = plt.subplots(1)ax.set_aspect('equal')# Show the imageax.imshow(img)# Now, loop through coord arrays, and create a circle at each x,y pairfor xx,yy in zip(x,y):    circ = Circle((xx,yy),50)    ax.add_patch(circ)# Show the imageplt.show()

enter image description here


To get the image, instead of plt.show do (Without saving to disc one can get it as):

io_buf = io.BytesIO()fig.savefig(io_buf, format='raw')#dpi=36)#DPI)io_buf.seek(0)img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),                         newshape=(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1))io_buf.close()plt.close()  #To not display the image