TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

OpenCV Mouse Event

OpenCV Mouse Event with What is OpenCV, History, Installation, Reading Images, Writing Images, Resize Image, Image Rotation, Gaussian Blur, Blob Detection, Face Detection and Face Recognition etc.

<< Back to OPENCV

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:

import cv2
mouse_events = [j for j in dir(cv2) if 'EVENT' in j]
print(mouse_events)

Above code will return a list of all mouse events that are supported by OpenCV.

Output:

['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']

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:

import cv2
import numpy as np
# Creating mouse callback function
def draw_circle(event,x,y,flags,param):
    if(event == cv2.EVENT_LBUTTONDBLCLK):
        	cv2.circle(img,(x,y),100,(255,255, 0),-1)
# Creating a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
    cv2.imshow('image',img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()

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:

import cv2
import numpy as np
draw = False # true if the mouse is pressed. Press m to shift into curve mode.
mode = True # if True, draw rectangle.
a,b = -1,-1
# mouse callback function
def draw_circle(event,x,y,flags,param):
    global a,b,draw,mode
    if(event == cv2.EVENT_LBUTTONDOWN):
        draw = True
        a,b = x,y
    elif (event == cv2.EVENT_MOUSEMOVE):
        if draw == True:
            if mode == True:
                cv2.rectangle(img,(a,b),(x,y),(0,255,0),-1)
            else:
                cv2.circle(img,(x,y),5,(0,0,255),-1)
    elif(event == cv2.EVENT_LBUTTONUP):
        draw = False
        if mode == True:
            cv2.rectangle(img,(a,b),(x,y),(0,255,0),-1)
        else:
            cv2.circle(img,(x,y),5,(0,0,255),-1)
# We bind the keyboard key m to toggle between rectangle and circle.
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif(k == 27):
        break
cv2.destroyAllWindows()

Output

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.






Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf