OpenCV Python – Handling Mouse Events
Mouse events in OpenCV allow you to create interactive applications where users can click, drag, and draw on images. This is very useful for building drawing tools, object selection systems, and real-time annotation applications.
In this tutorial, you will learn how to handle mouse events using OpenCV Python step by step.
1. What are Mouse Events in OpenCV?
Mouse events are actions performed using a mouse, such as:
- Left click
- Right click
- Mouse movement
- Dragging
- Double click
OpenCV provides a function called setMouseCallback() to handle these events.
2. Import OpenCV
import cv2
import numpy as np
3. Create a Blank Image
img = np.zeros((500, 500, 3), dtype=np.uint8)
4. Define Mouse Callback Function
This function detects mouse actions:
def draw_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img, (x, y), 10, (0, 255, 0), -1)
5. Set Mouse Callback
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", draw_event)
6. Display Image and Capture Events
while True:
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == 27: # ESC key
break
cv2.destroyAllWindows()
7. Full Working Example (Click to Draw Circles)
import cv2
import numpy as np
img = np.zeros((500, 500, 3), dtype=np.uint8)
def draw_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img, (x, y), 10, (0, 255, 0), -1)
cv2.namedWindow("Mouse Events")
cv2.setMouseCallback("Mouse Events", draw_event)
while True:
cv2.imshow("Mouse Events", img)
if cv2.waitKey(1) & 0xFF == 27:
break
cv2.destroyAllWindows()
8. Common Mouse Event Types
OpenCV supports many event types:
-
cv2.EVENT_LBUTTONDOWN→ Left click -
cv2.EVENT_LBUTTONUP→ Left release -
cv2.EVENT_RBUTTONDOWN→ Right click -
cv2.EVENT_MOUSEMOVE→ Mouse movement -
cv2.EVENT_LBUTTONDBLCLK→ Double click
9. Example: Draw Rectangle on Drag
drawing = False
ix, iy = -1, -1
def draw(event, x, y, flags, param):
global ix, iy, drawing, img
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
img_copy = img.copy()
cv2.rectangle(img_copy, (ix, iy), (x, y), (255, 0, 0), 2)
cv2.imshow("Image", img_copy)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
cv2.rectangle(img, (ix, iy), (x, y), (255, 0, 0), 2)
10. Real-World Applications
Mouse events are used in:
- Image annotation tools
- Object labeling systems
- Drawing applications
- AI dataset preparation tools
- Interactive UI systems
11. Common Mistakes
❌ Window not responding
✔ Solution:
-
Ensure
cv2.waitKey()is inside loop
❌ Drawing not visible
✔ Solution:
-
Use
.copy()when previewing shapes - Update window continuously
12. Conclusion
Handling mouse events in OpenCV Python allows you to build interactive computer vision applications. From simple drawing tools to advanced annotation systems, mouse events are essential for user-driven image processing.
Once you master this, you can build powerful GUI-based AI tools.


0 Comments