1#!/usr/bin/env python 2''' 3mouse_and_match.py [-i path | --input path: default ./] 4 5Demonstrate using a mouse to interact with an image: 6 Read in the images in a directory one by one 7 Allow the user to select parts of an image with a mouse 8 When they let go of the mouse, it correlates (using matchTemplate) that patch with the image. 9 ESC to exit 10''' 11import numpy as np 12import cv2 13 14# built-in modules 15import os 16import sys 17import glob 18import argparse 19from math import * 20 21 22drag_start = None 23sel = (0,0,0,0) 24 25def onmouse(event, x, y, flags, param): 26 global drag_start, sel 27 if event == cv2.EVENT_LBUTTONDOWN: 28 drag_start = x, y 29 sel = 0,0,0,0 30 elif event == cv2.EVENT_LBUTTONUP: 31 if sel[2] > sel[0] and sel[3] > sel[1]: 32 patch = gray[sel[1]:sel[3],sel[0]:sel[2]] 33 result = cv2.matchTemplate(gray,patch,cv2.TM_CCOEFF_NORMED) 34 result = np.abs(result)**3 35 val, result = cv2.threshold(result, 0.01, 0, cv2.THRESH_TOZERO) 36 result8 = cv2.normalize(result,None,0,255,cv2.NORM_MINMAX,cv2.CV_8U) 37 cv2.imshow("result", result8) 38 drag_start = None 39 elif drag_start: 40 #print flags 41 if flags & cv2.EVENT_FLAG_LBUTTON: 42 minpos = min(drag_start[0], x), min(drag_start[1], y) 43 maxpos = max(drag_start[0], x), max(drag_start[1], y) 44 sel = minpos[0], minpos[1], maxpos[0], maxpos[1] 45 img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) 46 cv2.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1) 47 cv2.imshow("gray", img) 48 else: 49 print "selection is complete" 50 drag_start = None 51 52if __name__ == '__main__': 53 parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images') 54 parser.add_argument("-i","--input", default='./', help="Input directory.") 55 args = parser.parse_args() 56 path = args.input 57 58 cv2.namedWindow("gray",1) 59 cv2.setMouseCallback("gray", onmouse) 60 '''Loop through all the images in the directory''' 61 for infile in glob.glob( os.path.join(path, '*.*') ): 62 ext = os.path.splitext(infile)[1][1:] #get the filename extenstion 63 if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm": 64 print infile 65 66 img=cv2.imread(infile,1) 67 if img == None: 68 continue 69 sel = (0,0,0,0) 70 drag_start = None 71 gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 72 cv2.imshow("gray",gray) 73 if (cv2.waitKey() & 255) == 27: 74 break 75 cv2.destroyAllWindows() 76