How to do it

You need to complete the following steps:

  1. Import the necessary modules:
import cv2import numpy as np
  1. Define a class that encapsulates mask creation:
class MaskCreator:    def __init__(self, image, mask):        self.prev_pt = None        self.image = image        self.mask = mask        self.dirty = False        self.show()        cv2.setMouseCallback('mask', self.mouse_callback)    def show(self):        cv2.imshow('mask', self.image)    def mouse_callback(self, event, x, y, flags, param):        pt = (x, y)        if event == cv2.EVENT_LBUTTONDOWN:            self.prev_pt = pt        elif event == cv2.EVENT_LBUTTONUP:            self.prev_pt = None        if self.prev_pt and flags & cv2.EVENT_FLAG_LBUTTON:            cv2.line(self.image, self.prev_pt, pt, (127,)*3, 5)            cv2.line(self.mask, self.prev_pt, pt, 255, 5)                            self.dirty = True self.prev_pt ...

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.