Python openCV matchTemplate断言失败16位图像



我正在尝试使用16位图像遵循本教程。对应的图像以231x291的数组形式存储,"大图像"为img。数组大小为51x107的"小图像"为"selected_img"。然而,我一直得到这个错误。

https://docs.opencv.org/4.x/d4/dc6/tutorial_py_template_matching.html

methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img.copy()
method = eval(meth)
# Apply template Matching
res = cv2.matchTemplate(img, selected_image, method)
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)
cv2.rectangle(img, top_left, bottom_right, 255, 2)
plt.subplot(121), plt.imshow(res, cmap='gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img, cmap='gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()

错误:

File "<ipython-input-19-61c72dbd3f62>", line 8, in <module>
res = cv2.matchTemplate(img, selected_image, method)
cv2.error: OpenCV(4.5.4) D:aopencv-pythonopencv-pythonopencvmodulesimgprocsrctemplmatch.cpp:1164: error: (-215:Assertion failed) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function 'cv::matchTemplate'

opencv matchTemplate()函数只接受8位或32位浮点类型,在这里的文档中提到

In matchTemplate()>参数在图片:图像搜索正在运行。必须为8位或32位浮点数

同样在你的错误中,你可以发现assert语句检查深度是否= CV_8U或CV_32F

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

matchTemplate接受32位浮点数(除了uint8)。FP32有23位尾数,所以你的16位值适合那里的而不会损失精度

img.astype(np.float32) 转换为np.float32

最新更新