Python技术迷

OpenCV教程-OpenCV模板匹配

整理:python技术迷

模板匹配是一种用于在较大图像中查找模板图像位置的技术。OpenCV提供了cv2.matchTemplates()函数来实现这个目的。它简单地滑动模板图像在输入图像上,并比较输入图像下的模板和图像块。

有各种方法可用于比较;我们将在后续主题中讨论一些流行的方法。

它返回一个灰度图像,其中每个像素表示该像素的邻域与输入模板的匹配程度。

OpenCV中的模板匹配

模板匹配包括以下步骤:

步骤1:获取实际图像并将其转换为灰度图像。

步骤2:选择模板作为灰度图像。

步骤3:查找准确度水平匹配的位置。这是通过将模板图像滑过实际图像来完成的。

步骤4:当结果大于准确度水平时,将该位置标记为检测到的位置。

考虑以下示例:
import cv2   import numpy as np   # Reading the main image   rgb_img = cv2.imread(r'C:\Users\DEVANSH SHARMA\rolando.jpg',1)  # It is need to be convert it to grayscale   gray_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2GRAY)   # Reading the template image   template = cv2.imread(r'C:\Users\DEVANSH SHARMA\ronaldo_face.jpg',0)   # Store width in variable w and height in variable h of template  w, h = template.shape[:-1]   # Now we perform match operations.   res = cv2.matchTemplate(gray_img,template,cv2.TM_CCOEFF_NORMED)   # Declare a threshold   threshold = 0.8  # Store the coordinates of matched location in a numpy array   loc = np.where(res >= threshold)   # Draw the 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)   # Now display the final matched template image   cv2.imshow('Detected',img_rgb)

输出:

Image

专属福利 

👉点击领取:最全Python资料合集

具有多个对象的模板匹配

在上面的例子中,我们在图像中搜索仅出现一次的模板图像。假设特定对象在特定图像中多次出现。在这种情况下,我们将使用阈值处理,因为cv2.minMaxLoc()不会给出模板图像的所有位置。考虑以下例子。
import cv2   import numpy as np   # Reading the main image   img_rgb = cv2.imread(r'C:\Users\DEVANSH SHARMA\mario.png',1)  # It is need to be convert it to grayscale   img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)   # Read the template   template = cv2.imread(r'C:\Users\DEVANSH SHARMA\coin1.png',0)   # Store width in variable w and height in variable h of template  w, h = template.shape[:-1]   # Now we perform match operations.   res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)   # Declare a threshold   threshold = 0.8  # Store the coordinates of matched region 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)   # Now display the final matched template image   cv2.imshow('Detected',img_rgb)

输出:

Image

在上述程序中,我们以著名的超级马里奥游戏的图像为主图像,以硬币图像为模板图像。硬币在主图像中多次出现。当它在图像中找到硬币时,它会在硬币上绘制矩形。

模板匹配的限制

在模板匹配中存在一些限制,如下所示:

  • 计算中等到大图像的模式相关图像是一项耗时的过程。

  • 模式出现必须保留参考模板图像的方向。

  • 模板匹配不适用于模板的旋转或缩放版本,因为形状/大小/剪切等的变化。

Image
 1

Image

热门推荐
Image