How to use Mouse Clicks to draw Circles in Python using OpenCV — Easy Project

Let’s do it…

Step 1 — Import the 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)

Step 3 — Create a draw circles function.

def draw_circles(event,x,y,flags,param):
if event==cv2.EVENT_LBUTTONDOWN:,(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:
if cv2.waitKey(1)==27:
  • 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.




Data Scientist || Blogger ||

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

9 Habits of Highly Successful Software Engineers

Oracle DB Transactions — Fuzzy read

Fifth Week of Coding 5th July — 9th July

Alibaba Cloud Releases EventBridge to Support Cloud Native Architecture

*..Increase or Decrease the Size of Static Partition in Linux..*

Difference Between User Guide And User Manual

Focus Time: Stay focused and beat procrastination counting the time

Alibaba Cloud DevOps Cookbook Part 2 — SSH and ECS Key Pairs

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhishek Sharma

Abhishek Sharma

Data Scientist || Blogger ||

More from Medium

How to Split and Merge Color Channels in cv2

Face mask detection with deep learning

OpenCV python library for processing multimedia files

Histogram of an Image with python