cv2鼠标事件标记和类型(MouseEventFlags、MouseEventTypes)

官方文档:
MouseEventFlags
MouseEventTypes

'''
EVENT_FLAG_ALTKEY = 32		摁住Alt
EVENT_FLAG_CTRLKEY = 8		摁住Ctrl

EVENT_FLAG_LBUTTON = 1		摁住左键
EVENT_FLAG_MBUTTON = 4		摁住中键
EVENT_FLAG_RBUTTON = 2		摁住右键
EVENT_FLAG_SHIFTKEY = 16	摁住Shift

EVENT_LBUTTONDBLCLK = 7		左键双击
EVENT_LBUTTONDOWN = 1		左键击下
EVENT_LBUTTONUP = 4			左键弹起
EVENT_MBUTTONDBLCLK = 9		中键双击
EVENT_MBUTTONDOWN = 3		中键击下
EVENT_MBUTTONUP = 6			中键弹起
EVENT_MOUSEHWHEEL = 11		滚动条向左,flags>0。向右,flags<0
EVENT_MOUSEMOVE = 0			鼠标移动
EVENT_MOUSEWHEEL = 10		滚动条向上,flags>0。向下,flags<0
EVENT_RBUTTONDBLCLK = 8		中键双击
EVENT_RBUTTONDOWN = 2		中键击下
EVENT_RBUTTONUP = 5			中键弹起
'''

PS:PyCharm社区版测试可用。可能专业版调用的后端不是Qt,某些不能用。

测试代码:

import cv2
import numpy as np


# 回调函数
def MouseEvent(event, x, y, flags, param):
    # print('[{},{}]'.format(x, y))  # 坐标,原点在左上角

    '''
    if flags == cv2.EVENT_FLAG_ALTKEY:
        print('摁住Alt')
    if flags == cv2.EVENT_FLAG_CTRLKEY:
        print('摁住Ctrl')
    if flags == cv2.EVENT_FLAG_SHIFTKEY:
        print('摁住Shift')

    if flags == cv2.EVENT_FLAG_LBUTTON:
        print('摁住左键')
    if flags == cv2.EVENT_FLAG_MBUTTON:
        print('摁住中键')
    if flags == cv2.EVENT_FLAG_RBUTTON:
        print('摁住右键')
    '''

    if event == cv2.EVENT_LBUTTONDBLCLK:
        print('左键双击')
    if event == cv2.EVENT_MBUTTONDBLCLK:
        print('中键双击')
    if event == cv2.EVENT_RBUTTONDBLCLK:
        print('右键双击')

    '''
    if event == cv2.EVENT_LBUTTONDOWN:
        print('左键击下')
    if event == cv2.EVENT_LBUTTONUP:
        print('左键弹起')
    if event == cv2.EVENT_MBUTTONDOWN:
        print('中键击下')
    if event == cv2.EVENT_MBUTTONUP:
        print('中键弹起')
    if event == cv2.EVENT_RBUTTONDOWN:
        print('右键击下')
    if event == cv2.EVENT_RBUTTONUP:
        print('右键弹起')
    '''

    if event == cv2.EVENT_MOUSEWHEEL:
        if flags > 0:
            print('向前滚动')
        else:
            print('向后滚动')
    if event == cv2.EVENT_MOUSEHWHEEL:
        if flags > 0:
            print('向左滚动')  # 按住Alt
        else:
            print('向右滚动')


if __name__ == '__main__':
    img = np.zeros((500, 500, 3), np.uint8)  # 500x500黑色背景
    cv2.namedWindow('test')
    cv2.setMouseCallback('test', MouseEvent)  # 窗口与回调函数绑定

    while True:
        cv2.imshow('test', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):  # 摁下q退出
            break
    cv2.destroyAllWindows()

你可能感兴趣的:(Python,OpenCV)