import cv2 import numpy as np def match_pattern(image, pattern): # 载入图像和模式 img = cv2.imread(image) pattern_img = cv2.imread(pattern) # 获取模式图像的宽高 pattern_height, pattern_width, _ = pattern_img.shape # 使用模板匹配算法进行匹配 result = cv2.matchTemplate(img, pattern_img, cv2.TM_CCOEFF_NORMED) # 设置匹配阈值 threshold = 0.8 # 寻找匹配结果中大于阈值的坐标 locations = np.where(result >= threshold) for loc in zip(*locations[::-1]): # 在原始图像上绘制矩形框标识匹配位置 cv2.rectangle(img, loc, (loc[0] + pattern_width, loc[1] + pattern_height), (0, 255, 0), 2) # 显示结果图像 cv2.imshow('Pattern Matching Result', img) cv2.waitKey(0) cv2.destroyAllWindows() # 调用函数进行模式匹配 match_pattern('rings.png', 'ring.png')
时间: 2024-04-09 20:30:41 浏览: 23
你好!你的代码看起来是对图像中的指定模式进行匹配,并在匹配位置上绘制矩形框。你调用了`match_pattern`函数,将原始图像和模式图像的文件名作为参数传递给函数。在这个例子中,你将原始图像命名为`rings.png`,将模式图像命名为`ring.png`。当你运行这段代码时,它会显示结果图像,其中匹配的位置用绿色矩形框标识出来。
请确保在运行代码之前,你已经安装了OpenCV库,并且将图像文件放置在正确的路径下。如果你想匹配不同的图像,可以将图像文件名替换成你自己的图像文件名。希望这能满足你的需求!如果有任何其他问题,请随时提问。