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:

Output:

mouse2 Implement Mouse Callback Events on Images using OpenCV in Python

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

Life2Coding

Technology Related Blog at Life2Coding
Feel free to contact us for your any kind of technical problems. We are here to help you.
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 *