Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/mouse_and_match.py
16337 views
1
#!/usr/bin/env python
2
'''
3
mouse_and_match.py [-i path | --input path: default ../data/]
4
5
Demonstrate 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
10
SPACE for next image
11
ESC to exit
12
'''
13
14
# Python 2/3 compatibility
15
from __future__ import print_function
16
17
import numpy as np
18
import cv2 as cv
19
20
# built-in modules
21
import os
22
import sys
23
import glob
24
import argparse
25
from math import *
26
27
28
drag_start = None
29
sel = (0,0,0,0)
30
31
def onmouse(event, x, y, flags, param):
32
global drag_start, sel
33
if event == cv.EVENT_LBUTTONDOWN:
34
drag_start = x, y
35
sel = 0,0,0,0
36
elif event == cv.EVENT_LBUTTONUP:
37
if sel[2] > sel[0] and sel[3] > sel[1]:
38
patch = gray[sel[1]:sel[3],sel[0]:sel[2]]
39
result = cv.matchTemplate(gray,patch,cv.TM_CCOEFF_NORMED)
40
result = np.abs(result)**3
41
_val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)
42
result8 = cv.normalize(result,None,0,255,cv.NORM_MINMAX,cv.CV_8U)
43
cv.imshow("result", result8)
44
drag_start = None
45
elif drag_start:
46
#print flags
47
if flags & cv.EVENT_FLAG_LBUTTON:
48
minpos = min(drag_start[0], x), min(drag_start[1], y)
49
maxpos = max(drag_start[0], x), max(drag_start[1], y)
50
sel = minpos[0], minpos[1], maxpos[0], maxpos[1]
51
img = cv.cvtColor(gray, cv.COLOR_GRAY2BGR)
52
cv.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)
53
cv.imshow("gray", img)
54
else:
55
print("selection is complete")
56
drag_start = None
57
58
if __name__ == '__main__':
59
print(__doc__)
60
61
parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images')
62
parser.add_argument("-i","--input", default='../data/', help="Input directory.")
63
args = parser.parse_args()
64
path = args.input
65
66
cv.namedWindow("gray",1)
67
cv.setMouseCallback("gray", onmouse)
68
'''Loop through all the images in the directory'''
69
for infile in glob.glob( os.path.join(path, '*.*') ):
70
ext = os.path.splitext(infile)[1][1:] #get the filename extension
71
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
72
print(infile)
73
74
img=cv.imread(infile,1)
75
if img is None:
76
continue
77
sel = (0,0,0,0)
78
drag_start = None
79
gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
80
cv.imshow("gray",gray)
81
if cv.waitKey() == 27:
82
break
83
cv.destroyAllWindows()
84
85