';对于';在OpenCv Python中进行模板匹配时循环不起作用。谁能告诉我为什么?我正在macOS X上运行代码

';对于';在OpenCv Python中进行模板匹配时循环不起作用。谁能告诉我为什么?我正在macOS X上运行代码,python,python-3.x,opencv,opencv3.0,template-matching,Python,Python 3.x,Opencv,Opencv3.0,Template Matching,代码的图像位于与此问题相关的链接中。 () 即使我将错误的图像作为“主”图像传递,模板仍然匹配。 甚至当我给出主图像和模板(实际上是主图像的一部分)时,“for”循环也无法运行,因为矩形从未在主图像上绘制。 至于代码,当你在谷歌上搜索“openCV python中的模板匹配”时,几乎所有的链接都可以找到它 # Python program to illustrate # template matching import cv2 import numpy as np # Read the mai

代码的图像位于与此问题相关的链接中。 () 即使我将错误的图像作为“主”图像传递,模板仍然匹配。 甚至当我给出主图像和模板(实际上是主图像的一部分)时,“for”循环也无法运行,因为矩形从未在主图像上绘制。 至于代码,当你在谷歌上搜索“openCV python中的模板匹配”时,几乎所有的链接都可以找到它

# Python program to illustrate
# template matching
import cv2
import numpy as np

# Read the main image
img_rgb = cv2.imread('test.jpg')

# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

# Read the template
template = cv2.imread('cropped1.jpg',0)

# Store width and heigth of template in w and h
w, h = template.shape[::-1]

# Perform match operations.
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)

# Specify a threshold
threshold = 0.8

# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold)

# Draw a rectangle around the matched region.
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)



# Show the final image with the matched area.
cv2.imshow('Detected',img_rgb)
cv2.waitKey(0)
(事实上,我认为这不会解决您的问题,因为您说模板匹配不起作用,但我会留下答案供将来使用,因为这也应该被检查,以确保for循环不会通过写入图像而使您的程序崩溃)

当你画一个矩形(或者其他任何东西)的时候,你应该非常确定你的矩形不会超出图像的大小。我认为,当您在此处添加w和h时,您的矩形终点超出了图像边界:

cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)

尝试这样的事情(可能有错误,我通常用C++代码,还没有检查这个片段),但是后面的想法应该是清楚的:

for pt in zip(*loc[::-1]):
    if pt[0] > 0 and pt[1]>0 and pt[0] < img_rgb.width and pt[1] < img_rgb.height
        endPt[0] = max(pt[0] + w, img_rgb.width)
        endPt[1] = max(pt[1] + h, img_rgb.height)
        cv2.rectangle(img_rgb, pt, endPt, (0,255,255), 2)
邮政编码中的邮政编码(*loc[:-1]): 如果pt[0]>0和pt[1]>0和pt[0]您可以复制代码并将其放在这里,人们会更容易帮助您完成。现在您可以解决这个问题了吗?如果您的图像、模板和所有内容都是完美的,那么问题可能在于阈值。将其降低到0.4-0.5左右,则更可能的是,for在没有任何可迭代的情况下仍能正常工作。W为什么不尝试一些调试,例如,检查
zip(*loc[::-1]
返回的内容?