如何计算通过模板匹配检测到的对象数? [英] How to count the number of objects detected with Template Matching?

查看:84
本文介绍了如何计算通过模板匹配检测到的对象数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关与opencv和python进行模板匹配的文档,并在最后一部分中涉及与多个对象进行模板匹配的文档,该代码检测了mario图像上的19个硬币,但是,是否可以计算使用python上的一些函数,例如len()或任何opencv方法?

I was reading the docs about template matching with opencv and python and in the last part about template matching with multiple objects, the code detect the 19 coins on the mario image but, is it possible to count the number of objects detected with some function on python like len() or any opencv method?

以下是本教程中显示的代码: http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html

Here is the code showed on the tutorial: http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html

模板匹配代码:

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('mario_coin.png',0)
w, h = template.shape[::-1]

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

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

结果是: Mario Bros&硬币

那么,有什么方法可以计数在图像上检测到的硬币并在终端上打印数字? 像这样:

So, is there any way to count the coins detected on the image and print the number on the terminal? Something like:

The Template Matching code showed before...

print "Function that detect number of coins with template matching"
>>> 19

推荐答案

我发现了一个合适的解决方案(针对我的应用),如Ulrich所建议的那样,它可以计算唯一的匹配项.这并不理想,但是在我的应用程序中使用敏感性"通常会产生+/- 2%的结果.

I found a suitable solution (for my application) in counting unique matches as Ulrich suggested. It's not ideal, but playing with the "sensitivity" normally yields results within +/- 2% for my application.

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('mario_coin.png',0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)

f = set()

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

    sensitivity = 100
    f.add((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))

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

found_count = len(f)

这篇关于如何计算通过模板匹配检测到的对象数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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