How to detect a click in python opencv

Viewed 43

I do follow this https://www.geeksforgeeks.org/displaying-the-coordinates-of-the-points-clicked-on-the-image-using-python-opencv/

# importing the module
import cv2
  
# function to display the coordinates of
# of the points clicked on the image
def click_event(event, x, y, flags, params):
 
    # checking for left mouse clicks
    if event == cv2.EVENT_LBUTTONDOWN:
 
        # displaying the coordinates
        # on the Shell
        print(x, ' ', y)
        p1 = (x,y)
        print('p1 =', p1)
        # displaying the coordinates
        # on the image window
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, str(x) + ',' +
                    str(y), (x,y), font,
                    1, (255, 0, 0), 2)
        cv2.imshow('image', img)
 
# driver function
if __name__=="__main__":
 
    # reading the image
    img = cv2.imread('lena.jpg', 1)
 
    # displaying the image
    cv2.imshow('image', img)
 
    # setting mouse handler for the image
    # and calling the click_event() function
    cv2.setMouseCallback('image', click_event)
 
    # wait for a key to be pressed to exit
    cv2.waitKey(0)
 
    # close the window
    cv2.destroyAllWindows()

now on p1 = (x,y) if I want detect other click on other(p2) how can I do. thank for read and hope you can help me :)

1 Answers

So from my understanding you want to increase the number every time you click. If so this is how you would do that, apologies if I misunderstood.

i = 1
def click_event(event, x, y, flags, params):

# checking for left mouse clicks
if event == cv2.EVENT_LBUTTONDOWN:
    global i
    # displaying the coordinates
    # on the Shell
    print(x, ' ', y)
    p1 = (x,y)
    txt = ('p{num: d} =')
    print(txt.format(num=i), p1)
    i +=1
    # displaying the coordinates
    # on the image window
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(img, str(x) + ',' +
                str(y), (x,y), font,
                1, (255, 0, 0), 2)
    cv2.imshow('image', img)
Related