/OpenCV-2.4.2/samples/python2/mouse_and_match.py

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