Thursday, September 21, 2023

User Interaction in OpenCV- Draw Polygon with Mouse

Similar to drawing circles, this example will draw polygons with the mouse. OpenCV provides cv2.polylines() function to draw polylines or polygons.

cv2.polylines(img, points, is_closed,color, thickness)

points specify the vertexes (the corner points of a polygon) of the polygons/polylines, is_closed=True will draw a closed polygon, if False, draw the polylines. Other parameters are the same as the cv2.circle() in the previous post.

This example works in this way, every time the mouse left key is clicked, a point is added to the polygon, when the mouse is moving a thin line is drawn between the last point and the mouse current point to indicate where the line will be drawn.

When the right key is clicked the final polygon will be drawn with all points. 


 The source codes are very similar to the previous example of drawing circles, we will not explain it line by line here. The only difference is that an array is used to store the vertexes for the polygon when the EVENT_ LBUTTONDOWN (left button down) events happen, the polygon is drawn based on the array of the vertexes.

When the mouse is moving, a thin line is drawn with drawing_color between the last point in the array and the current mouse point, this thin line is changing along with the mouse moving to indicate the line.

When the mouse right click happens, the EVENT_RBUTTONDOWN event is captured, then the drawing is completed, and the final polygon will be drawn with final_color.

Execute the code in DrawPolygonWithMouse.py and you are able to draw polygons with your mouse, the results are something like Figure shown above.

Share:

0 comments:

Post a Comment