{ "title": "def template_matching(img_big, img_small, threshold=0.8,isShow=False):\n '''\n 使用模板匹配算法来大图中找小图\n :param img_big: 大图数据 例如:cv2.imread("test2.png")\n :param img_small: 小图数据 例如: cv2.imread('X1.png')\n :param threshold: 匹配度阈值 默认 0.8\n :param isShow: 是否显示结果 默认 False\n :return: 结果坐标列表[]\n '''\n # 读取大图和小图\n if type(img_big)==str:\n img_big = cv2.imread(img_big)\n if type(img_small)==str:\n img_small = cv2.imread(img_small)\n image = img_big\n template = img_small\n # 确保输入图像是二维的\n # if len(image.shape) > 2:\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # # 确保输入图像是二维的\n # if len(template.shape) > 2:\n # template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\n\n # 获取小图的宽度和高度\n template_width, template_height = template.shape[:2]\n\n # 使用模板匹配方法\n result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)\n\n # 使用np.where()函数找到匹配结果\n locations = np.where(result >= threshold)\n res_loc=[]\n # 在大图中标记匹配的小图\n for loc in zip(*locations[::-1]):#列表进行反转,然后通过解包的方式传递给 zip() 函数\n cv2.rectangle(image, loc, (loc[0] + template_width, loc[1] + template_height), (0, 255, 0), 2)\n logger.debug(f"符合区域:{loc[0]},{loc[1]}, {loc[0] + template_width}, {loc[1] + template_height}")\n res_loc.append({"x":loc[0],"y":loc[1],"width":loc[0]+ template_width,"height":loc[1] + template_height,})\n\n if isShow:\n if res_loc !=[]:\n cv2.imshow('Matched Template', image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return res_loc\n\n为什么明明找到是一个横向的长方形,,而框出来会变成竖的方框内容:这是因为在绘制矩形框时,cv2.rectangle()函数的第二个参数为左上角坐标,第三个参数为右下角坐标。而在代码中,绘制矩形框的坐标为(loc[0], loc[1])和(loc[0] + template_width, loc[1] + template_height)。根据代码,左上角的坐标是(loc[0], loc[1]),右下角的坐标是(loc[0] + template_width, loc[1] + template_height)。因此,绘制出来的矩形框是竖向的。\n\n如果希望绘制横向的矩形框,可以将绘制矩形框的代码修改为:\n\ncv2.rectangle(image, loc, (loc[0] + template_width, loc[1] + template_height), (0, 255, 0), 2)\n\n这样就可以得到横向的矩形框了。

Python 图像模板匹配算法:在图片中查找目标区域

原文地址: http://www.cveoy.top/t/topic/qA9r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录