cv2.matchTemplate 函数与模板和图像不匹配后,如何阻止程序执行?

How to stop the program from getting executed after cv2.matchTemplate function does not match the template and image?

我想在模板匹配方法中创建一个 if/else,这样我就可以打印是否匹配。但是每当函数 cv2.matchTemplate 没有得到匹配时,它只是抛出一个错误而不是 returning 一些值。那么我如何将它 return 给我一个整数值,以便我可以用它来进行比较呢?基本上,我如何阻止它抛出错误,而不是 return 一些值以防不匹配?

错误是:cv2.error: /tmp/opencv20160107-54198-1duzac3/opencv-2.4.12/modules/imgproc/src/templmatch.cpp:251: 错误: (-215) img.rows >= templ.rows && img.cols >= templ.cols 函数 matchTemplate

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('image.jpg',0)
template = cv2.imread('template.jpg',0)
w, h = template.shape[::-1]

methods = ['cv2.TM_CCOEFF_NORMED','cv2.TM_SQDIFF']
res=cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
if res.any():
    print "match"
else:
    print "no match"

OpenCV Error: Assertion failed (img.rows >= templ.rows && img.cols >= templ.cols)

这表明您的模板尺寸大于您尝试 运行 匹配的图像,因此我会尝试先调整我的模板尺寸,然后再检查它们的尺寸。

Basically, how do I stop it from throwing an error and instead return some value in case of no match?

您可以 运行 在 try 块中处理代码本身,并捕获 cv2.error exception,例如:

try:
    res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
    if res.any():
        # do your process
except cv2.error as e: 
    # print "No match was found"
    # return something

或者,如果您更喜欢这种变体:

try:
    res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
    ok = True
except cv2.error as e: 
    ok = False      

if ok:
    # something