Skip to content

Commit b9c79bb

Browse files
authored
template matching class
1 parent b0f1a4c commit b9c79bb

6 files changed

Lines changed: 60 additions & 0 deletions

File tree

templatematch/findtext.jpg

451 KB
Loading

templatematch/mask.jpg

2 KB
Loading

templatematch/t2.jpg

116 KB
Loading

templatematch/template.jpg

3.45 KB
Loading

templatematch/template.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# template matching
2+
import cv2
3+
import numpy as np
4+
from scipy import signal
5+
from pprint import pprint
6+
from matplotlib import pyplot as plt
7+
8+
def show_img(title, img):
9+
cv2.namedWindow(f"{title}", cv2.WINDOW_NORMAL)
10+
cv2.imshow(f"{title}", img)
11+
cv2.waitKey(0)
12+
13+
14+
# 需要處理成透明背景 應該就可以找到對的物體進行辨識
15+
path1 = "t2.jpg"
16+
path2 = "template1.jpg"
17+
18+
img = cv2.imread(path1, 0)
19+
20+
template = cv2.imread(path2, 0)
21+
w = template.shape[1]
22+
h = template.shape[0]
23+
mask_img = np.where(template > 0, 100, 0)
24+
mask_img = np.float32(mask_img)
25+
26+
cv2.imwrite("mask.jpg", mask_img)
27+
28+
res = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED, mask=mask_img)
29+
30+
cv2.normalize(res, res, 0, 1, cv2.NORM_MINMAX, -1)
31+
32+
loc = np.where(res > 0.85)
33+
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
34+
print(len(loc[0]))
35+
i = 0
36+
tmp_point = []
37+
x, y = (0, 0)
38+
bottom_right = (max_loc[0] + w, max_loc[1] + h)
39+
cv2.rectangle(img, max_loc, bottom_right, (0, 0, 0), 2)
40+
imm = img[max_loc[1]:bottom_right[1], max_loc[0]:bottom_right[0]]
41+
for pt in sorted(zip(*loc[::-1]), key=lambda s: s[0]):
42+
if np.sqrt((x - pt[0]) ** 2 + (y - pt[1]) ** 2) < 500:
43+
continue
44+
45+
x, y = pt
46+
tmp_point.append(pt)
47+
# print(pt, (pt[0] + w, pt[1] + h))
48+
# cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 0), 1)
49+
50+
x, y = (0, 0)
51+
for pt in sorted(tmp_point, key=lambda s: s[1]):
52+
if np.sqrt((y - pt[1]) ** 2) < 150:
53+
continue
54+
x, y = pt
55+
print(pt)
56+
# cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 0), 1)
57+
show_img("test", img)
58+
cv2.imwrite("template.jpg", imm)
59+
# min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
60+
# print(min_val, max_val, min_loc, max_loc)

templatematch/template1.jpg

21.3 KB
Loading

0 commit comments

Comments
 (0)