To process the mouse click events we define the click_and_crop callback function on Line 10. We also define two global variables on Lines 7 and 8: refPt, which is a list of two (x, y)-coordinates specifying the rectangular region we are going to crop from our image, and cropping, a boolean indicating whether we are in cropping mode or not. We’ll start by importing our two necessary packages: argparse for parsing command line arguments and cv2 for our OpenCV bindings. # draw a rectangle around the region of interestĬv2.rectangle(image, refPt, refPt, (0, 255, 0), 2) # record the ending (x, y) coordinates and indicate that # check to see if the left mouse button was released # (x, y) coordinates and indicate that cropping is being # if the left mouse button was clicked, record the starting # grab references to the global variables # whether cropping is being performed or notĭef click_and_crop(event, x, y, flags, param): # initialize the list of reference points and boolean indicating Open up a new file, name it click_and_crop.py, and we’ll get to work: # import the necessary packages Let’s go ahead and get this example started. Capturing mouse click events with Python and OpenCV In order to run this example, you’ll need Python 2.7 and OpenCV 2.4.X.
Open canvas 6 mouse code#
Looking for the source code to this post? Jump Right To The Downloads Section