Site icon Machine Learning Projects

How to use mouse clicks to draw circles in Python using OpenCV – easy project – 2023

Machine Learning Projects

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.

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

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

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()
Final results

Do let me know if there’s any query regarding how to draw circles by contacting me by 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

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net.

Exit mobile version