0

An image opens on running my code in terminal or in Spyder. But there is no action on doing either left or right click. Here is the code I've written:

import cv2
import matplotlib.pyplot as plt

def drawCircle(event,x,y,flags,param):

    if event == cv2.EVENT_LBUTTONDOWN: #(If Left button of mouse clicked)
        cv2.circle(img,(x,y),radius = 100, color =(255,0,0),thickness=-1)
    if event == cv2.EVENT_RBUTTONDOWN: #(If Right button of mouse clicked)
        cv2.circle(img,(x,y),radius = 100, color =(0,255,0),thickness=-1)

img= np.zeros(shape=(512,512,3),dtype=np.int8)
cv2.namedWindow("someimage")

cv2.setMouseCallback("someimage", drawCircle)

while True:
    cv2.imshow("someimage",img)
    if cv2.waitKey(2):
        break

cv2.destroyAllWindows()
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Sri
  • 11
  • 1

1 Answers1

1

You're missing an import:

import numpy as np

Also, when no key is pressed for the specified delay (2ms in your case), waitkey returns -1. So cv2.waitKey(2) call evaluates to a truthy value and break is executed. Change it to

if cv2.waitKey(2) == ord("q"):
    break

This will stop the loop only when you press key q

I also noticed that right clicking will open a context menu first. Here is the link to the solution:
Why does a right click open a drop down menu in my OpenCV imshow() window?

Kashinath Patekar
  • 1,083
  • 9
  • 23
  • Wow i just added that check ==ord("q") and now my left click makes a blue circle and right click make a green circle, and on pressing q, my window got closed. Brilliant. Thanks for the help. Btw, Right click is not creating context click problem for me. – Sri May 18 '20 at 17:37