From a8698388079f46dcb92278e3f4874bf80320dced Mon Sep 17 00:00:00 2001 From: Alexander Mordvintsev Date: Mon, 19 Sep 2011 06:28:39 +0000 Subject: [PATCH] RectSelector in common.py --- samples/python2/common.py | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/samples/python2/common.py b/samples/python2/common.py index e6586029cc..43d22b3492 100644 --- a/samples/python2/common.py +++ b/samples/python2/common.py @@ -114,4 +114,37 @@ def nothing(*arg, **kw): pass def clock(): - return cv2.getTickCount() / cv2.getTickFrequency() \ No newline at end of file + return cv2.getTickCount() / cv2.getTickFrequency() + +class RectSelector: + def __init__(self, win, callback): + self.win = win + self.callback = callback + cv2.setMouseCallback(win, self.onmouse) + self.drag_start = None + self.drag_rect = None + def onmouse(self, event, x, y, flags, param): + x, y = np.int16([x, y]) # BUG + if event == cv2.EVENT_LBUTTONDOWN: + self.drag_start = (x, y) + if self.drag_start: + if flags & cv2.EVENT_FLAG_LBUTTON: + #h, w = self.frame.shape[:2] + xo, yo = self.drag_start + x0, y0 = np.minimum([xo, yo], [x, y]) + x1, y1 = np.maximum([xo, yo], [x, y]) + #x0, y0 = np.maximum(0, np.minimum([xo, yo], [x, y])) + #x1, y1 = np.minimum([w, h], np.maximum([xo, yo], [x, y])) + self.drag_rect = None + if x1-x0 > 0 and y1-y0 > 0: + self.drag_rect = (x0, y0, x1, y1) + else: + if self.drag_rect: + self.callback(self.drag_rect) + self.drag_start = None + self.drag_rect = None + def draw(self, vis): + if not self.drag_rect: + return + x0, y0, x1, y1 = self.drag_rect + cv2.rectangle(vis, (x0, y0), (x1, y1), (0, 255, 0), 2)