Javatpoint Logo
Javatpoint Logo

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.



Draw Circle

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:

OpenCV Mouse Event

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:


OpenCV Mouse Event

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.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA