Drawing dynamic shapes

Th next example gives you an introduction into how to handle mouse events with OpenCV. The cv2.setMouseCallback() function performs this functionality. The signature for this method is as follows:

cv2.setMouseCallback(windowName, onMouse, param=None)

This function establishes the mouse handler for the window named windowName. The onMouse function is the callback function, which is called when a mouse event is performed (for example, double-click, left-button down, left-button up, among others). The optional param parameter is used to pass additional information to the callback function. 

So the first step is to create the callback function:

# This is the mouse callback function:
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
print("event: EVENT_LBUTTONDBLCLK")
cv2.circle(image, (x, y), 10, colors['magenta'], -1)

if event == cv2.EVENT_MOUSEMOVE:
print("event: EVENT_MOUSEMOVE")

if event == cv2.EVENT_LBUTTONUP:
print("event: EVENT_LBUTTONUP")

if event == cv2.EVENT_LBUTTONDOWN:
print("event: EVENT_LBUTTONDOWN")

The draw_circle() function receives the specific event and the coordinates (x, y) for every mouse event. In this case, when a left double-click (cv2.EVENT_LBUTTONDBLCLK) is performed, we draw a circle in the corresponding (x, y) coordinates on the event.

Additionally, we have also printed some messages in order to see other produced events, but we do not use them to perform any additional actions.

The next step is to create a named window. In this case, we named it Image mouse. This named window is where the mouse callback function will be associated with:

# We create a named window where the mouse callback will be established
cv2.namedWindow('Image mouse')

And finally, we set (or activate) the mouse callback function to the function we created before:

# We set the mouse callback function to 'draw_circle'
cv2.setMouseCallback('Image mouse', draw_circle)

In summary, when a left double-click is performed, a filled magenta circle is drawn centered at the (x, y) position of the performed double-click. The full code for this example can be seen in the mouse_drawing.py script.