Python OpenCV模板匹配错误

Fre*_*xyz 12 python opencv

我一直在为python的OpenCV绑定搞乱一段时间了,我想尝试模板匹配,我得到这个错误,我不知道为什么

C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\templmatch.cpp:910: error: (-215) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function cv::matchTemplate
Run Code Online (Sandbox Code Playgroud)

任何人都有任何关于为什么会发生这种情况的线索?

源代码:

import win32gui
from PIL import ImageGrab
import win32api, win32con
import numpy
deckVar = "deck.png" # Temporary

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

margin = 10

def OOO(): # Order Of Operations
    print None

def main():
    deck = "test"

    img = ImageGrab.grab()

    HWNDHandle = win32gui.FindWindow(None, "Hearthstone");
    x,y,x2,y2 = win32gui.GetWindowRect(HWNDHandle)
    print x,y,x2,y2
    l = x2-x
    h = y2-y
    print l,h

    img_recog(img,"imgs/my_collection.png")

def img_recog(img,templ):
    import cv2
    import numpy as np
    from matplotlib import pyplot as plt


    img2 = numpy.array(img.getdata()).reshape(img.size[0], img.size[1], 3)
    template = cv2.imread(templ,0)
    w, h = template.shape[::-1]

    # All the 6 methods for comparison in a list
    methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
                'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']


    img = img2.copy()
    method = eval(methods[1])

    # Apply template Matching
    try:
        res = cv2.matchTemplate(img,template,method)
    except Exception as e:
        print str(e)
        raw_input()
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)


    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    return cv2.rectangle(img,top_left, bottom_right, 255, 2)


main()  
Run Code Online (Sandbox Code Playgroud)

Ela*_*eph 17

注意错误信息:

错误:(-215)(深度== CV_8U ||深度== CV_32F)&& type == _templ.type()&& _img.dims()<= 2 in function cv :: matchTemplate

这意味着图像的数据类型应为CV_8U或CV_32F,并且它应具有3个或更少的通道.

如果您不知道CV_8U,CV_32F的含义,请参阅此列表.

可能你传递的是np.uint8或np.float32以外的numpy对象.您可以使用以下命令轻松将numpy dtype转换为8位或32位:

img.astype(np.float32)
img.astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)

请注意OpenCV期望CV_8U 8位数据在0..255范围内,CV_32F可以在任何范围内.

  • 为了检查图像的深度或匹配模板,打印 img.dtype/template.dtype。至于通道,它是 image.shape 中的第三个值——去掉应该为 2 或更少,而不是 3 或更少的通道,如评论中所述——尝试将它们转换为灰色。 (2认同)