Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python opencv-如何在没有缩放的情况下进行模板匹配?_Python_Opencv - Fatal编程技术网

Python opencv-如何在没有缩放的情况下进行模板匹配?

Python opencv-如何在没有缩放的情况下进行模板匹配?,python,opencv,Python,Opencv,我在试着配纸牌。我认为,由于这些卡片都是唯一的,所以模板匹配可能是正确的方法 我把模板(图像)放在一个文件夹中,这些就是卡片 现在,当我尝试将它们与图片中的几个卡片和表格进行匹配时,我在阈值=0.8时得到了0个匹配项 我读了一遍,这似乎是一个规模问题。i、 e.如果我理解正确,如果卡片图片(模板)与我想要检测卡片的图片(模板)不在同一比例上,则不会被检测到 我不知道如何从这里开始 这是我正在使用的代码 mport pyautogui import cv2 import numpy as np i

我在试着配纸牌。我认为,由于这些卡片都是唯一的,所以模板匹配可能是正确的方法

我把
模板
(图像)放在一个文件夹中,这些就是卡片

现在,当我尝试将它们与图片中的几个卡片和表格进行匹配时,我在
阈值=0.8时得到了0个匹配项

我读了一遍,这似乎是一个规模问题。i、 e.如果我理解正确,如果卡片图片(模板)与我想要检测卡片的图片(模板)不在同一比例上,则不会被检测到

我不知道如何从这里开始

这是我正在使用的代码

mport pyautogui
import cv2
import numpy as np
import time
import pyscreenshot as grabimage
import os


img_de = cv2.imread('/media/xxx/cards/match2.jpg')
img_gray = cv2.cvtColor(img_de,cv2.COLOR_BGR2GRAY)

os.chdir('/media/xxx/cards/template-for-matching/')
templates = os.listdir()
# templates = ['9s.jpg']
for template in templates:
    print('checking: ' + str(template))
    t = cv2.imread(template,0)
    w,h = t.shape[::-1]
    res = cv2.matchTemplate(img_gray,t,cv2.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where(res >= threshold)

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

    cv2.imshow('detected',img_de)
    cv2.waitKey(0)
    input('Wait')
    cv2.destroyAllWindows()
编辑:

被接受的答案起作用

我采用了不同的方法,因为我的用例是特定的,我可以更改获取
模板
图像和
测试图像的比例

我正在使用以下命令确保比例保持不变。(Ubuntu,终端命令)


这是一个答案:

您应该创建参考图像的金字塔,请参阅。然后在代码中添加一个外部循环,该循环覆盖所有图像大小。在这个金字塔中,您将获取具有最强匹配的模板,并对该匹配设置阈值

请参阅以下代码:

#在图像上循环查找模板
对于glob.glob(args[“images”]+“/*.jpg”)中的imagePath:
#加载图像,将其转换为灰度,然后初始化
#用于跟踪匹配区域的簿记变量
image=cv2.imread(imagePath)
灰色=cv2.CVT颜色(图像,cv2.COLOR\u BGR2GRAY)
找到=无
#在图像的比例上循环
对于np.linspace(0.2,1.0,20)[:-1]中的比例:
#根据比例调整图像大小,并保持跟踪
#调整大小的比率
resized=imutils.resize(灰色,宽度=int(灰色.shape[1]*比例))
r=gray.shape[1]/浮动(已调整大小的.shape[1])
#如果调整大小的图像小于模板,则断开
#从循环
如果调整了.shape[0]found[0]:
找到=(maxVal、maxLoc、r)
#解包簿记变量并计算(x,y)坐标
#根据调整大小的比例调整边界框的大小
(u,maxLoc,r)=找到
(startX,startY)=(int(maxLoc[0]*r),int(maxLoc[1]*r))
(endX,endY)=(int((maxLoc[0]+tW)*r),int((maxLoc[1]+tH)*r))
#在检测到的结果周围绘制边界框并显示图像
cv2.矩形(图像,(startX,startY),(endX,endY),(0,0,255),2)
cv2.imshow(“图像”,图像)
cv2.等待键(0)

也许您可以发布一些示例图像。通常,模板匹配仅适用于移位,而不适用于缩放或旋转不同的图像。如果是后者,则主要需要在每个缩放和旋转时进行处理。如果你有方向、视角和比例的变化,那么你可以考虑特征匹配。我不能对他的回答置评,因为我是一个新用户。这种方法做得很好,当大小不完全相同时,计算出的相关性会较弱,但仍然会得到比背景噪声地板更高的分数。我在过去实现过这个,并且从经验中知道。然后请展示代码和示例图像以获得正确的答案。如果您没有发布图像的权限,您可以发布到一些免费的主机服务,并将URL放在这里。@fmw42这样看起来可以吗?是的,好多了。谢谢。@neatnib谢谢你的回答,我可以知道如何检查%年龄的准确性吗?我将result=cv2.TM\u CCOEFF更改为cv2.TM\u CCOEFF\u normaled,并添加了
threshold=0.97 loc=np。其中(res>=threshold)
,它给出了一个空数组,但代码仍然给出了一个匹配。如何在比赛中保持一定程度的信心?
# Install wmctrl
sudo apt-get install wmctrl
# Command to resize the window
wmctrl -r string -e 0,left,up,width,height
# loop over the images to find the template in
for imagePath in glob.glob(args["images"] + "/*.jpg"):
    # load the image, convert it to grayscale, and initialize the
    # bookkeeping variable to keep track of the matched region
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    found = None

    # loop over the scales of the image
    for scale in np.linspace(0.2, 1.0, 20)[::-1]:
        # resize the image according to the scale, and keep track
        # of the ratio of the resizing
        resized = imutils.resize(gray, width = int(gray.shape[1] * scale))
        r = gray.shape[1] / float(resized.shape[1])

        # if the resized image is smaller than the template, then break
        # from the loop
        if resized.shape[0] < tH or resized.shape[1] < tW:
            break
        # detect edges in the resized, grayscale image and apply template
        # matching to find the template in the image
        edged = cv2.Canny(resized, 50, 200)
        result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
        (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)

        # check to see if the iteration should be visualized
        if args.get("visualize", False):
            # draw a bounding box around the detected region
            clone = np.dstack([edged, edged, edged])
            cv2.rectangle(clone, (maxLoc[0], maxLoc[1]),
                (maxLoc[0] + tW, maxLoc[1] + tH), (0, 0, 255), 2)
            cv2.imshow("Visualize", clone)
            cv2.waitKey(0)

        # if we have found a new maximum correlation value, then update
        # the bookkeeping variable
        if found is None or maxVal > found[0]:
            found = (maxVal, maxLoc, r)

    # unpack the bookkeeping variable and compute the (x, y) coordinates
    # of the bounding box based on the resized ratio
    (_, maxLoc, r) = found
    (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
    (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r))

    # draw a bounding box around the detected result and display the image
    cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
    cv2.imshow("Image", image)
    cv2.waitKey(0)