Python OpenCV 模板匹配 - 识别图片并获取坐标和尺寸
def template_matching(img_big, img_small, threshold=0.8):
# 读取大图和小图
image = img_big
template = img_small
# 获取小图的宽度和高度
template_width, template_height = template.shape[:2]
# 使用模板匹配方法
result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
# 使用np.where()函数找到匹配结果
locations = np.where(result >= threshold)
res_loc=[]
# 在大图中标记匹配的小图
for loc in zip(*locations[::-1]):#列表进行反转,然后通过解包的方式传递给 zip() 函数
x = loc[0]
y = loc[1]
width = x + template_width
height = y + template_height
cv2.rectangle(image, (x, y), (width, height), (0, 255, 0), 2)
print('识别区域', x, y, width, height)
res_loc.append({'x':x, 'y':y, 'width':width, 'height':height})
return res_loc
该代码使用 OpenCV 库的模板匹配功能,在图像中识别目标区域,并获取目标区域的坐标和尺寸。
步骤:
- 读取大图和小图
- 使用
cv2.matchTemplate()函数进行模板匹配 - 使用
np.where()函数找到匹配结果 - 循环遍历匹配结果,在图像中绘制矩形框,并获取坐标和尺寸
参数:
img_big: 大图img_small: 小图 (模板)threshold: 匹配阈值,默认值为 0.8
返回值:
res_loc: 一个列表,包含所有匹配区域的坐标和尺寸信息,每个元素为一个字典,包含 'x', 'y', 'width', 'height' 四个键值对。
注意:
- 模板匹配的准确性受图像质量、阈值和模板尺寸的影响
- 在使用该代码之前,请确保已经安装了 OpenCV 库
示例用法:
# 加载图片
img_big = cv2.imread('big_image.jpg')
img_small = cv2.imread('small_image.jpg')
# 进行模板匹配
res_loc = template_matching(img_big, img_small)
# 打印匹配结果
for loc in res_loc:
print(loc)
该代码示例展示了如何使用 template_matching() 函数进行模板匹配,并将匹配结果打印到控制台。
其他相关资源:
- OpenCV 文档: https://opencv.org/
- Python OpenCV 模板匹配教程: https://www.pyimagesearch.com/2015/01/20/template-matching-with-python-and-opencv/
总结:
该代码提供了一个简单易懂的模板匹配示例,可以帮助开发者在图像中识别目标区域,并获取目标区域的坐标和尺寸。开发者可以根据自己的实际需求对代码进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/qAcD 著作权归作者所有。请勿转载和采集!