- Import the modules:
import cv2import numpy as np
- 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
- Display the image, and, after the rectangle has been completed and the A button ...