在Python中使用OpenCV进行模板匹配 [英] Template Matching Using OpenCV in Python

查看:360
本文介绍了在Python中使用OpenCV进行模板匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是图像处理和模板匹配的新手,可以从

I am a newbie in Image Processing and learning about Template Matching by getting some help from OpenCV documentation, but I didn't understand some lines of the code.
Here is the code:

import cv2
import numpy as np
from matplotlib import pyplot as plt
img_rgb = cv2.imread('mario.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('coin.png', 0)
w, h = template.shape[::-1]
count = 0

res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
    count += 1
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

cv2.imwrite('res.png', img_rgb)
print(count)

目标是在超级马里奥地图中对硬币进行模板匹配.
我的问题:
1.在循环for pt in zip(*loc[::-1]):中,我放置了一个计数器,当我打印它时,它会打印65,而硬币的数量仅为19.
2.变量threshold=0.8的功能是什么,当我更改其值时,结果图像也会更改.

The objective is to template match the coin in the super mario map.
My Questions :
1. In the loop for pt in zip(*loc[::-1]): I put a counter and when I print it, it prints 65, whereas the number of coins is only 19.
2. What is the function of the variable threshold=0.8, when I change its value, the resulting image is changed.

有人可以帮助我回答我的问题吗? 预先谢谢你.

Can anyone help me to answer my question? Thank you in advance.

推荐答案

阈值0.8表示匹配至少应为模板图像和目标感兴趣区域的80%.因此,如果大于805,则为硬币.如果降低阈值,那么即使不是硬币,假阳性结果也会增加.

threshold 0.8 means the match should be at least 80% of template image and the source Region of interest. thus if it is greater than 805 it is a coin. if you reduce the threshold the false positive results would increase even if it is not a coin.

Zip(* loc [::-1])中的pt:此命令用于值大于阈值的点. zip是包含所有这些点的容器,它将迭代到所有这些点,并在此封闭实体(即此处的硬币)周围绘制矩形.

for pt in Zip(*loc[::-1]): this command is for the points which have values greater than threshold. zip is container of all such points and it will iterate to all such points and draw rectangle around this closed entity i.e. coins here.

希望这有助于理解:)

这篇关于在Python中使用OpenCV进行模板匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆