How to do it...

  1. Import the modules:
import cv2import numpy as np
  1. Open an image and define the mouse callback function to draw a rectangle on the image:
img = cv2.imread('../data/Lena.png', cv2.IMREAD_COLOR)show_img = np.copy(img)mouse_pressed = Falsey = x = w = h = 0def mouse_callback(event, _x, _y, flags, param):    global show_img, x, y, w, h, mouse_pressed    if event == cv2.EVENT_LBUTTONDOWN:        mouse_pressed = True        x, y = _x, _y        show_img = np.copy(img)    elif event == cv2.EVENT_MOUSEMOVE:        if mouse_pressed:            show_img = np.copy(img)            cv2.rectangle(show_img, (x, y),                          (_x, _y), (0, 255, 0), 3)    elif event == cv2.EVENT_LBUTTONUP:        mouse_pressed = False        w, h = _x - x, _y - y
  1. Display the image, and, after the rectangle has been completed and the A button ...

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.