Click response on video output using Events in OpenCV – Python
Fellow Coders, in this tutorial section we are going to create a program with click response on video output using events in OpenCV Python library. We will use “cv2.EVENT_LBUTTONDOWN” in case whenever the left mouse button is clicked. Through this function in OpenCV, we can increase user interaction and user experience. We will be applying this function on a video output device: in this case, your webcam output.
Various functions used:
We will be using various other OpenCV functions such as namedWindow() for creating a window, setMouseCallback() for setting the mouse handler for the specified window, resize() resizing the frame and circle() for drawing a circle with a specified radius every time you interact(click) with the window.
Importing the required libraries:
import numpy as np import cv2 as cv
These are the two most important libraries. np is for numerical operations and cv2 is the OpenCV library.
Next, we are going to Use OpenCV’s VideoCapture function:
cap = cv2.VideoCapture(0)
Let’s define the color, line width, radius and the initial point for the circle we will be drawing when the event occurs:
color = (0,255,0) line_width = 3 radius = 100 point = (0,0)
Now, we will define a function that will record the event:
def click(event, x, y, flags, param): global point, pressed if event == cv2.EVENT_LBUTTONDOWN: print("Pressed",x,y) point = (x,y)
After defining the click() function, we will now use the namedWindow() and setMouseCallback() function:
cv2.namedWindow("Frame") cv2.setMouseCallback("Frame",click)
Finally, we will capture the video input and draw a circle when the event occurs:
while(True): ret, frame = cap.read() frame = cv2.resize(frame, (0,0), fx=0.5,fy=0.5) cv2.circle(frame, point, radius, color, line_width) cv2.imshow("Frame",frame) ch = cv2.waitKey(1) if ch & 0xFF == ord('q'): break
At last, we will use OpenCV’s release() and destroyAllWindows() functions:
cap.release() cv2.destroyAllWindows()
Let’s look at the entire Python code for click response on video output using Events in OpenCV:
import numpy as np import cv2 cap = cv2.VideoCapture(0) color = (0,255,0) line_width = 3 radius = 100 point = (0,0) def click(event, x, y, flags, param): global point, pressed if event == cv2.EVENT_LBUTTONDOWN: print("Pressed",x,y) point = (x,y) cv2.namedWindow("Frame") cv2.setMouseCallback("Frame",click) while(True): ret, frame = cap.read() frame = cv2.resize(frame, (0,0), fx=0.5,fy=0.5) cv2.circle(frame, point, radius, color, line_width) cv2.imshow("Frame",frame) ch = cv2.waitKey(1) if ch & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Leave a Reply