Mouse Events – OpenCV 3.4 with python 3 Tutorial 27
Draw circles:
[python]
import cv2
import numpy as np
def mouse_drawing(event, x, y, flags, params):
if event == cv2.EVENT_LBUTTONDOWN:
print("Left click")
circles.append((x, y))
cap = cv2.VideoCapture(0)
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", mouse_drawing)
circles = []
while True:
_, frame = cap.read()
for center_position in circles:
cv2.circle(frame, center_position, 5, (0, 0, 255), -1)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1)
if key == 27:
break
elif key == ord("d"):
circles = []
cap.release()
cv2.destroyAllWindows()
[/python]
Draw rectangle:
[python]
import cv2
import numpy as np
drawing = False
point1 = ()
point2 = ()
def mouse_drawing(event, x, y, flags, params):
global point1, point2, drawing
if event == cv2.EVENT_LBUTTONDOWN:
if drawing is False:
drawing = True
point1 = (x, y)
else:
drawing = False
elif event == cv2.EVENT_MOUSEMOVE:
if drawing is True:
point2 = (x, y)
cap = cv2.VideoCapture(0)
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", mouse_drawing)
while True:
_, frame = cap.read()
if point1 and point2:
cv2.rectangle(frame, point1, point2, (0, 255, 0))
cv2.imshow("Frame", frame)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
[/python]
Hi there, I’m founder of Pysource.
I help Companies, Freelancers and Students to learn easily and efficiently how to apply visual recognition to their projects.
For Consulting/Contracting Services, check out this page.
Most Read:
-
Train YOLO to detect a custom object (online with free GPU)
-
YOLO object detection using Opencv with Python
-
Detecting colors (Hsv Color Space) – Opencv with Python
-
How to install Python 3 and Opencv 4 on Windows
-
Check if two images are equal with Opencv and Python
-
YOLO V3 – Install and run Yolo on Nvidia Jetson Nano (with GPU)
-
How to install Dlib for Python 3 on Windows
-
Feature detection (SIFT, SURF, ORB) – OpenCV 3.4 with python 3 Tutorial 25