Python OpenCV 模板匹配错误

标签 python opencv

我已经弄乱了 python 的 OpenCV 绑定(bind)有一段时间了,我想尝试模板匹配,我得到了这个错误,我不知道为什么

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

有人知道为什么会发生这种情况吗?

源代码:

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()  

最佳答案

注意报错信息:

error: (-215) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function cv::matchTemplate

意思是图像的数据类型应该是CV_8U或CV_32F,并且它应该有3个或更少的 channel 。

如果您不知道 CV_8U、CV_32F 的含义,请参阅 this list .

可能您正在传递 np.uint8 或 np.float32 以外的 numpy 对象。 您可以使用以下方法轻松地将 numpy dtype 转换为 8 位或 32 位:

img.astype(np.float32)
img.astype(np.uint8)

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

关于Python OpenCV 模板匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592950/

相关文章:

android - 导入android项目时出现问题

.net - 视频中移动物体速度测量算法

python - 霍夫线变换以在图像中查找多边形

python - 如何在HSV opencv python中指定颜色的上限值和下限值

python - 尝试在 QGraphicsScene 和 QGraphicsView 中显示 opencv 视频,但没有显示任何内容

python - 发布 Python 代码的最佳网站?

python - 使用 Python 导入模块(PyCogent)

python - 如何在我的机器上安装 numpy/core/numeric.py 文件;我想要 isclose()

python - 领域特定语言,标准文件格式

python - 使用 OPENCV python 裁剪面部