Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7a6f380

Browse files
committed
update ch24
1 parent c0cf9fa commit 7a6f380

File tree

3 files changed

+42
-21
lines changed

3 files changed

+42
-21
lines changed

‎ch24-模板匹配/matchTemplate.py‎ renamed to ‎ch24-模板匹配/24.1-OpenCV中的模板匹配-matchTemplate.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@
22
__author__ = 'play4fun'
33
"""
44
create time:15-10-24 下午5:46
5+
原理
6+
模板匹配是用来在一副大图中搜寻查找模版图像位置的方法。OpenCV 为 我们提供了函数 cv2.matchTemplate()。
7+
和 2D 卷积一样 它也是用模板图像在输入图像 大图 上滑动 并在每一个位置对模板图像和与其对应的 输入图像的子区域 比较。
8+
OpenCV 提供了几种不同的比较方法 细节 看 文档 。
9+
返回的结果是一个灰度图像 每一个像素值 示了此区域与模板的匹配 程度。
10+
如果输入图像的大小是 WxH
11+
模板的大小是 wxh 输出的结果 的大小就是 W-w+1 H-h+1 。
12+
当你得到这幅图之后 就可以使用函数 cv2.minMaxLoc() 来找到其中的最小值和最大值的位置了。
13+
第一个值为矩形左上角的点 位置
14+
w h 为 moban 模板矩形的宽和 。
15+
这个矩形就是 找到的模板区域了。
516
"""
617

718
import cv2
@@ -16,6 +27,7 @@
1627
# All the 6 methods for comparison in a list
1728
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
1829
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
30+
1931
for meth in methods:
2032
img = img2.copy()
2133

@@ -41,5 +53,5 @@
4153
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
4254
plt.subplot(122), plt.imshow(img, cmap='gray')
4355
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
44-
plt.suptitle('method: '+meth)
56+
plt.suptitle('method: '+meth)
4557
plt.show()
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'''
2+
假如你的目标对 只在图像中出现了很多次怎么办呢
3+
函数 cv.imMaxLoc() 只会给出最大值和最小值。此时 我们就 使用阈值了。
4+
在下 的例子中我们 经典游戏 Mario 的一张截屏图片中找到其中的硬币
5+
6+
'''
7+
8+
import cv2
9+
import numpy as np
10+
11+
# from matplotlib import pyplot as plt
12+
13+
img_rgb = cv2.imread('../data/mario.png')
14+
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
15+
template = cv2.imread('../data/mario_coin.png', 0)
16+
w, h = template.shape[::-1]
17+
18+
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
19+
threshold = 0.8
20+
loc = np.where(res >= threshold)
21+
print(len(loc))
22+
23+
for pt in zip(*loc[::-1]):
24+
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)
25+
print("rectangle 1")
26+
27+
# cv2.imwrite('res.png',img_rgb)
28+
cv2.imshow("result", img_rgb)
29+
cv2.waitKey(0)

‎ch24-模板匹配/Multiple-Objects.py‎

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /