About Lesson
In this lesson we are going to learn about Python OpenCV Working Mouse Events, basically in this lesson we want to learn by clicking the mouse draw circle or rectangle.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import cv2 import numpy as np windowname = "Drawing In OpenCV" image = np.zeros((512,512,3), np.uint8) cv2.namedWindow(windowname) def draw_shape(event, x,y, flags, params): if event == cv2.EVENT_LBUTTONDBLCLK: #cv2.rectangle(image, (x, y), (400, 200), # (255, 0, 0), 6) cv2.circle(image, (x, y), 60, (0, 0, 255), -1) cv2.setMouseCallback(windowname, draw_shape) def main(): while(True): cv2.imshow(windowname, image) if cv2.waitKey(20) == 27: break cv2.destroyAllWindows() if __name__ == "__main__": main() |
First we need to create an empty image using Numpy.
1 |
image = np.zeros((512,512,3), np.uint8) |
So in here we are checking, if we double press the left mouse button, we want to draw rectangle or circle, there are different mouse buttons that we can use, in here we want to use left mouse button.
1 2 3 4 |
if event == cv2.EVENT_LBUTTONDBLCLK: #cv2.rectangle(image, (x, y), (400, 200), # (255, 0, 0), 6) cv2.circle(image, (x, y), 60, (0, 0, 255), -1) |
If you run the code and double press the left mouse button you will see the circle.