opencv的鼠标事件的双击和单击事件

首先跟着https://dream.blog.csdn.net/article/details/112335340的学习,发现opencv的鼠标事件中,双击时会同步触发2次单击事件。因此,使用线程对双击和单击事件处理。

import cv2 as cv
import time
import _thread

click_num = 0
IS_EVENT_LBUTTONDBLCLK = 0

# 编写回调函数
def draw_circle(event, x, y, flags, param):
    if event == cv.EVENT_LBUTTONDBLCLK:
        _thread.start_new_thread(fun_EVENT_LBUTTONDBLCLK,(x,y))
    # 鼠标左键按下去,实心圆
    elif event == cv.EVENT_LBUTTONDOWN:
        # time.sleep(0.5)
        # if IS_EVENT_LBUTTONDBLCLK == 0:
        #     cv.circle(img, center=(x, y), radius=5, color=(255, 0, 0), thickness=-1)
    # 鼠标右键按下去,空心圆
        # click_num+=1
        # print("单击:%d" %click_num)
        _thread.start_new_thread(fun_EVENT_LBUTTONDOWN, (x,y))
    elif event == cv.EVENT_RBUTTONDOWN:
        cv.circle(img, center=(x, y), radius=5, color=(0, 255, 0), thickness=1)

def fun_EVENT_LBUTTONDBLCLK(x,y):
    global click_num
    global IS_EVENT_LBUTTONDBLCLK
    IS_EVENT_LBUTTONDBLCLK = 1
    cv.circle(img, center=(x, y), radius=20, color=(0, 255, 0), thickness=1)
    click_num+=1
    print("双击:%d" %click_num)
    time.sleep(1)
    IS_EVENT_LBUTTONDBLCLK = 0

def fun_EVENT_LBUTTONDOWN(x,y):
    global click_num
    global IS_EVENT_LBUTTONDBLCLK
    time.sleep(0.5)
    if IS_EVENT_LBUTTONDBLCLK == 1:
        return
    else:
        cv.circle(img, center=(x, y), radius=5, color=(255, 0, 0), thickness=-1)
        # 鼠标右键按下去,空心圆
        click_num+=1
        print("单击:%d" %click_num)



img = cv.imread(r'/home/pi/Pictures/day13.png', -1)

cv.namedWindow(winname='drawing')
cv.setMouseCallback('drawing', draw_circle)

while True:
    cv.imshow('drawing', img)
    # 按 q 键退出
    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cv.destroyAllWindows()


import cv2
events = [i for i in dir(cv2) if 'EVENT' in i]
print(events)



# event 具体说明如下:

# EVENT_MOUSEMOVE 0 //滑动
# EVENT_LBUTTONDOWN 1 //左键点击
# EVENT_RBUTTONDOWN 2 //右键点击
# EVENT_MBUTTONDOWN 3 //中键点击
# EVENT_LBUTTONUP 4 //左键放开
# EVENT_RBUTTONUP 5 //右键放开
# EVENT_MBUTTONUP 6 //中键放开
# EVENT_LBUTTONDBLCLK 7 //左键双击
# EVENT_RBUTTONDBLCLK 8 //右键双击
# EVENT_MBUTTONDBLCLK 9 //中键双击
# flags 具体说明如下:

# EVENT_FLAG_LBUTTON 1 //左键拖曳
# EVENT_FLAG_RBUTTON 2 //右键拖曳
# EVENT_FLAG_MBUTTON 4 //中键拖曳
# EVENT_FLAG_CTRLKEY 8 //(8~15)按 Ctrl 不放
# EVENT_FLAG_SHIFTKEY 16 //(16~31)按 Shift 不放
# EVENT_FLAG_ALTKEY 32 //(32~39)按 Alt 不放



 

你可能感兴趣的:(鼠标事件,单击,双击,opencv)