참조: http://www.pyimagesearch.com/2015/03/09/capturing-mouse-click-events-with-python-and-opencv/
위 두 참조의 코드를 조합하여 만듬.
함수
class MouseControl: def __init__(self): # self.points = [] self.refPt = [] self.cropping = False self.retRect = [] # def getPoint(self, event, x, y, flags, params): # if event == cv2.EVENT_LBUTTONCLK: # self.points = [x, y] def click_and_crop(self, event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: self.refPt = [(x, y)] self.cropping = True elif event == cv2.EVENT_LBUTTONUP: self.refPt.append((x, y)) self.cropping = False # left, top, right, bottom self.retRect = [mousectrl.refPt[0][1], mousectrl.refPt[0][0], mousectrl.refPt[1][1], mousectrl.refPt[1][0]] self.refPt = [] return self.retRect
실제사용
# if mouse has an input,cv2.namedWindow('img1') cv2.setMouseCallback('img1', mousectrl.click_and_crop) # for t in range(2):while(1): cv2.imshow('img1', img1) k = cv2.waitKey(20) & 0xFF # print mousectrl.refPt if k == ord('n'): break if len(mousectrl.retRect) == 4: break mousectrl.retRect[0] << leftmousectrl.retRect[2] << right
mousectrl.retRect[1] << top
mousectrl.retRect[3] << bottom mousectrl.retRect = []