OpenCV Mouse Event
Mouse as a Paint Brush
OpenCV provides a facility to use the mouse as a paint brush or a drawing tool. Whenever any mouse event occurs on the window screen, it can draw anything. Mouse events can be left-button down, left-button up, double-click, etc. It gives us the coordinates (x,y) for every mouse event. By using these coordinates, we can draw whatever we want. To get the list of all available events, run the following code in the terminal:
Above code will return a list of all mouse events that are supported by OpenCV.
['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']
To draw a circle on the window screen, we first need to create a mouse callback function by using the cv2.setMouseCallback() function. It has a specific format that remains same everywhere. Our mouse callback function is facilitated by drawing a circle using double-click. Consider the following program:
In the above code, we first created a black window screen where the mouse event has occurred. When we double-click on the black window, it will draw a circle as we defined in the callback draw_circle() function.
Draw Rectangle and Curve
We can draw any shape on the window screen. We draw either rectangles or circles (depending on the model we select) by dragging the mouse as we do in Paint application. We consider the example where we created a callback function that has two parts. The first part is to draw the rectangle and another part to draw the circles. Let see the given example to understand it in more specific way:
In the above program, we have created two mouse callback functions. It is bound with the OpenCV window. In the while loop, we set a keyboard binding for key 'm' to shift between rectangle and curve.