OpenCV错误:cv2.matchTemplate()中的断言失败

时间:2018-03-20 17:53:16

标签: python python-3.x opencv

我目前正在开展一个项目,目标是识别一个"符号"来自相机流。为此,我使用cv2.matchTemplate()函数。我正在使用RasPi 3B和RasPi相机模块V2来获取视频。我遇到了一个错误,我认为它是由错误的模板路径引起的,但在检查后我发现路径正确。

以下是视频形状和模板形状的打印

frame.shape= [480,640,3]

t0.shape= [300,300,3] (I will make this one smaller, probably to like [30,30,3])

我的主要代码:

import numpy as np
import cv2
import time
import argparse
import imutils
from picamera.array import PiRGBArray
from picamera import PiCamera

ap = argparse.ArgumentParser()
ap.add_argument("-t0", "--template0", required = True, help = "Cesta k 
templatu pro cmd0")
args = vars(ap.parse_args())

t0 = cv2.imread(args["template0"])
w, h,_ = t0.shape[::-1]

camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))

time.sleep(0.1)

for f in camera.capture_continuous(rawCapture, format="bgr", 
use_video_port=True):
    frame = f.array

    print(frame.shape)
    print(t0.shape)

    frame = imutils.resize(frame, width = 300)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    res = cv2.matchTemplate(gray, t0, cv2.TM_CCOEFF_NORMED) #the error throwing line
    treshold = 0.8
    loc = np.where(res >= treshold)

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

    cv2.imshow("Frame", frame)
    rawCapture.truncate(0)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

我收到的错误消息:

OpenCV Error: Assertion failed ((depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2) in matchTemplate, file /home/pi/opencv-3.3.0/modules/imgproc/src/templmatch.cpp, line 1102
Traceback (most recent call last):
  File "tmplRec_fin1.py", line 43, in <module>
    res = cv2.matchTemplate(gray, t0, cv2.TM_CCOEFF_NORMED)
cv2.error: /home/pi/opencv-3.3.0/modules/imgproc/src/templmatch.cpp:1102: error: (-215) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function matchTemplate

1 个答案:

答案 0 :(得分:0)

(代表作者提问)

这正是造成这个问题的原因,老实说,我不明白我是如何犯这样一个愚蠢的错误的。希望它能帮助将来的某个人。

简而言之:导致问题的原因是我尝试将灰度视频流与rgb模板匹配,但这并不起作用。我认为它与图像的深度或它的通道有关。确保将灰度与灰度进行比较。