OpenCV 模板匹配错误:Assertion failed (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function 'cv::matchTemplate'
OpenCV 模板匹配错误:Assertion failed (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function 'cv::matchTemplate'
在使用 OpenCV 进行模板匹配时,您可能会遇到以下错误:
Assertion failed) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function 'cv::matchTemplate'
这个错误通常是由于模板图像和原始图像的深度和类型不匹配导致的。请确保模板图像和原始图像的深度和类型相同。可以通过使用cv2.IMREAD_GRAYSCALE参数读取图像来确保它们的深度为8位。
错误代码示例:
import cv2
import numpy as np
# 读取原始图像和模板图像
img = cv2.imread('image.jpg', 0)
template = cv2.imread('template.jpg', 0)
# 对原始图像进行边缘检测
edges = cv2.Canny(img, 100, 200)
# 使用匹配模板进行模板匹配
result = cv2.matchTemplate(edges, template, cv2.TM_CCOEFF_NORMED)
# 设置匹配阈值
threshold = 0.8
loc = np.where(result >= threshold)
# 在原始图像中绘制矩形框标记匹配位置
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + template.shape[1], pt[1] + template.shape[0]), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
修改后的代码:
import cv2
import numpy as np
# 读取原始图像和模板图像
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
template = cv2.imread('template.jpg', cv2.IMREAD_GRAYSCALE)
# 对原始图像进行边缘检测
edges = cv2.Canny(img, 100, 200)
# 使用匹配模板进行模板匹配
result = cv2.matchTemplate(edges, template, cv2.TM_CCOEFF_NORMED)
# 设置匹配阈值
threshold = 0.8
loc = np.where(result >= threshold)
# 在原始图像中绘制矩形框标记匹配位置
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + template.shape[1], pt[1] + template.shape[0]), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
这样修改后,应该可以解决这个报错。
原文地址: https://www.cveoy.top/t/topic/l5mp 著作权归作者所有。请勿转载和采集!