-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTemplateMatching.py
49 lines (40 loc) · 1.96 KB
/
TemplateMatching.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import numpy as np
import cv2
def TemplateMatching(src, temp, stepsize): # src: source image, temp: template image, stepsize: the step size for sliding the template
mean_t = 0;
var_t = 0;
location = [0, 0];
# Calculate the mean and variance of template pixel values
# ------------------ Put your code below ------------------
max_corr = 0;
# Slide window in source image and find the maximum correlation
for i in np.arange(0, src.shape[0] - temp.shape[0], stepsize):
for j in np.arange(0, src.shape[1] - temp.shape[1], stepsize):
mean_s = 0;
var_s = 0;
corr = 0;
# Calculate the mean and variance of source image pixel values inside window
# ------------------ Put your code below ------------------
# Calculate normalized correlation coefficient (NCC) between source and template
# ------------------ Put your code below ------------------
if corr > max_corr:
max_corr = corr;
location = [i, j];
return location
# load source and template images
source_img = cv2.imread('source_img.jpg',0) # read image in grayscale
temp = cv2.imread('template.jpg',0) # read image in grayscale
location = TemplateMatching(source_img, temp, 20);
print(location)
match_img = cv2.cvtColor(source_img, cv2.COLOR_GRAY2RGB)
# Draw a red rectangle on match_img to show the template matching result
# ------------------ Put your code below ------------------
# Save the template matching result image (match_img)
# ------------------ Put your code below ------------------
# Display the template image and the matching result
cv2.namedWindow('TemplateImage', cv2.WINDOW_NORMAL)
cv2.namedWindow('MyTemplateMatching', cv2.WINDOW_NORMAL)
cv2.imshow('TemplateImage', temp)
cv2.imshow('MyTemplateMatching', match_img)
cv2.waitKey(0)
cv2.destroyAllWindows()