python - Python cv2与主图像不匹配模板
问题描述
我有我的主要形象:
还有我的模板:
但是,我使用的 cv2 代码没有生成矩形来显示匹配,但我也收到 0 个错误。
这是代码:
# Read the main image
img_rgb = cv2.imread('main.png')
# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# Read the template
template = cv2.imread('temp.png',0)
template = np.array(template[:,::-1])
# Store width and height of template in w and h
w, h = template.shape[::-1]
# Perform match operations.
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
# Specify a threshold
threshold = 0.8
# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold)
# Draw a rectangle around the matched region.
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)
# Show the final image with the matched area.
cv2.imshow('Detected',img_rgb)
cv2.waitKey()
cv2.destroyAllWindows()
我最初的想法是模板图像太大而无法与主图像匹配,但是这是我第一次使用 cv2,我不确定如何修复它。
解决方案
我一直使用的模板匹配代码都是将模板的尺寸与图像的尺寸进行匹配。在您的情况下,您已经将源图像转换为灰度,更改
template = np.array(template[:,::-1])
w, h = template.shape[::-1]
(这可能不会做你想做的事)
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
w, h = template.shape
推荐阅读
- javascript - Axios 请求中调用函数(然后)[Vuejs]
- php - laravel 关系是否足以构建一个好的数据库?
- svg - SVG - 在不知道 svg 高度的情况下让线条垂直居中
- java - 等待自动缩放开始
- php - Unable to loop through values using for - Laravel 5.6 Blade Template
- c++ - 可变参数与非可变参数函数模板重载偏序
- websocket - 如何在adonis js websocket控制器中登录用户
- c# - ICalendar (ICS) - 只有 VEVENT 组件适用于 Outlook/googleCalendar
- java - 如何使用 intellij IDEA 停止重新格式化大括号上的中断
- c# - 如何确定var的大小?