In today’s very short blog we will see that how we can use mouse clicks to draw circles in Python using OpenCV. This is going to be a fun application. So let’s tighten our belts and dive straight into it.
Let’s do it…
Step 1 – Importing necessary libraries to draw circles.
import cv2 import numpy as np
Step 2 – Let’s create a black image.
black_image = np.zeros((512,512,3),np.uint8) cv2.imshow('Black Image', black_image)
NOTE – Read more about it here.
Step 3 – Create a draw circles function.
def draw_circles(event,x,y,flags,param): if event==cv2.EVENT_LBUTTONDOWN: cv2.circle(black_image,(x,y),40,(255,255,255),-1)
- event here refers to ay of the mouse operation.
- (x,y) are the coordinates of the point where we have clicked.
- Then we are checking if the event is equal to the left button click then draw a white colored circle centered at (x,y) with a radius of 40 pixels and filled with white color (because the thickness is passed as -1).
Step 4 – Run an infinite loop…
# draw circles while True: cv2.setMouseCallback('win',draw_circles) cv2.imshow('win',black_image) if cv2.waitKey(1)==27: break
- In the first line, we have used cv2.setMouseCallback() to bind the draw circles() function with the ‘win’ window. It means that as soon as something is done using the mouse on the ‘win’ window, immediately go to the draw_circles function and run that function.
- After that, we are just showing our black image with white circles drawn on it.
- And at last, if the ESC key(ASCII 27) is pressed break the code.
Let’s see the whole code…
import cv2 import numpy as np black_image = np.zeros((512, 512, 3), np.uint8) cv2.imshow('Black Image', black) def draw_circles(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(black_image, (x, y), 40, (255, 255, 255), -1) while True: cv2.setMouseCallback('win', draw_circles) cv2.imshow('win', black_image) if cv2.waitKey(1) == 27: break cv2.destroyAllWindows()
Do let me know if there’s any query regarding how to draw circles by contacting me on email or LinkedIn.
So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time ?…
Read my previous post: HOW TO DENOISE AN IMAGE USING MEDIAN BLUR IN PYTHON USING OPENCV‘