学习opencv的setMouseCallBack()函数

    1. import cv2 as cv
    2. import numpy as np
    3. # 鼠标的回调函数
    4. def draw_circie(event, x, y, flags, param):
    5. if event == cv.EVENT_LBUTTONDBLCLK:
    6. cv.circle(img, (x, y), 100, (255, 0, 0), -1)
    7. # 创建一个黑色图像
    8. img = np.zeros((512, 512, 3), np.uint8)
    9. # 面板
    10. cv.namedWindow("xx")
    11. # 绑定鼠标
    12. cv.setMouseCallback("xx", draw_circie)
    13. while True:
    14. cv.imshow("xx", img)
    15. if cv.waitKey(25) == 27:
    16. break
    17. cv.destroyWindow("images")

    鼠标点击绘制

    1. import numpy as np
    2. import cv2 as cv
    3. # 鼠标回调函数
    4. def draw_circle(event, x, y, flags, param):
    5. global ix, iy, drawing, mode
    6. if event == cv.EVENT_LBUTTONDOWN:
    7. drawing = True
    8. ix, iy = x, y
    9. elif event == cv.EVENT_MOUSEMOVE:
    10. if drawing == True:
    11. if mode == True:
    12. cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
    13. else:
    14. cv.circle(img, (x, y), 5, (0, 0, 255), -1)
    15. elif event == cv.EVENT_LBUTTONUP:
    16. drawing = False
    17. if mode == True:
    18. cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
    19. else:
    20. cv.circle(img, (x, y), 5, (0, 0, 255), -1)
    21. drawing = False # 如果按下鼠标,则为真
    22. mode = True # 如果为真,绘制矩形。按 m 键可以切换到曲线
    23. ix, iy = -1, -1
    24. img = np.zeros((512, 512, 3), np.uint8)
    25. cv.namedWindow('image')
    26. cv.setMouseCallback('image', draw_circle)
    27. while True:
    28. cv.imshow("image", img)
    29. if cv.waitKey(25) == 27:
    30. break
    31. cv.destroyAllWindows()