Life2Coding
Implement Mouse Callback Events on Images using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to implement mouse callback functions using OpenCV library and Python coding.

Documentation:

Python: cv2.setMouseCallback(windowName, onMouse[, param]) → None

Sets mouse handler for the specified window

Parameters:          

  • winname – Window name
  • onMouse – Name of the callback function. Whenever mouse events related to the above window occur, this callback function will be called. This function should have the signature like the following
    • void FunctionName (event, x, y, flags, userdata)
      • event – Type of the mouse event. These are the entire list of mouse events
        • EVENT_MOUSEMOVE
        • EVENT_LBUTTONDOWN
        • EVENT_RBUTTONDOWN
        • EVENT_MBUTTONDOWN
        • EVENT_LBUTTONUP
        • EVENT_RBUTTONUP
        • EVENT_MBUTTONUP
        • EVENT_LBUTTONDBLCLK
        • EVENT_RBUTTONDBLCLK
        • EVENT_MBUTTONDBLCLK
      • x – x coordinate of the mouse event
      • y – y coordinate of the mouse event
      • flags – Specific condition whenever a mouse event occurs. See the next OpenCV example code for the usage of this parameter. Here is the entire list of enum values which will be possesed by “flags”
        • EVENT_FLAG_LBUTTON
        • EVENT_FLAG_RBUTTON
        • EVENT_FLAG_MBUTTON
        • EVENT_FLAG_CTRLKEY
        • EVENT_FLAG_SHIFTKEY
        • EVENT_FLAG_ALTKEY
  • userdata – The optional parameter passed to the callback.

Steps:

  • Create window using cv2.namedWindow()
  • Register mouse callback using cv2.setMouseCallback()
  • Display Image using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np

# Create a black image and a window
windowName = 'MouseCallback'
img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow(windowName)

def CallBackFunc(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print("Left button of the mouse is clicked - position (", x, ", ",y, ")")
    elif event == cv2.EVENT_RBUTTONDOWN:
        print("Right button of the mouse is clicked - position (", x, ", ", y, ")")
    elif event == cv2.EVENT_MBUTTONDOWN:
        print("Middle button of the mouse is clicked - position (", x, ", ", y, ")")
    elif event == cv2.EVENT_MOUSEMOVE:
        print("Mouse move over the window - position (", x, ", ", y, ")")
    if flags == cv2.EVENT_FLAG_CTRLKEY + cv2.EVENT_FLAG_LBUTTON:
        print("Left mouse button is clicked while pressing CTRL key - position (", x, ", ",y, ")")
    elif flags == cv2.EVENT_FLAG_RBUTTON + cv2.EVENT_FLAG_SHIFTKEY:
        print("Right mouse button is clicked while pressing SHIFT key - position (", x, ", ", y, ")")
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_ALTKEY:
        print("Mouse is moved over the window while pressing ALT key - position (", x, ", ", y, ")")

# bind the callback function to window
cv2.setMouseCallback(windowName, CallBackFunc)


def main():
    while (True):
        cv2.imshow(windowName, img)
        if cv2.waitKey(20) == 27:
            break

    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()

Output:

mouse2 Implement Mouse Callback Events on Images using OpenCV in Python

life2coding_icon [] Implement Mouse Callback Events on Images using OpenCV in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.