Match template python cv2

Match template python cv2

In this chapter, you will learn

  • To find objects in an image using Template Matching
  • You will see these functions : cv.matchTemplate(), cv.minMaxLoc()

Theory

Template Matching is a method for searching and finding the location of a template image in a larger image. OpenCV comes with a function cv.matchTemplate() for this purpose. It simply slides the template image over the input image (as in 2D convolution) and compares the template and patch of input image under the template image. Several comparison methods are implemented in OpenCV. (You can check docs for more details). It returns a grayscale image, where each pixel denotes how much does the neighbourhood of that pixel match with template.

If input image is of size (WxH) and template image is of size (wxh), output image will have a size of (W-w+1, H-h+1). Once you got the result, you can use cv.minMaxLoc() function to find where is the maximum/minimum value. Take it as the top-left corner of rectangle and take (w,h) as width and height of the rectangle. That rectangle is your region of template.

Note If you are using cv.TM_SQDIFF as comparison method, minimum value gives the best match.

Template Matching in OpenCV

Here, as an example, we will search for Messi’s face in his photo. So I created a template as below:

Читайте также:  One page javascript template

messi_face.jpg

We will try all the comparison methods so that we can see how their results look like:

Источник

Template Matching¶

Template Matching is a method for searching and finding the location of a template image in a larger image. OpenCV comes with a function cv2.matchTemplate() for this purpose. It simply slides the template image over the input image (as in 2D convolution) and compares the template and patch of input image under the template image. Several comparison methods are implemented in OpenCV. (You can check docs for more details). It returns a grayscale image, where each pixel denotes how much does the neighbourhood of that pixel match with template.

If input image is of size (WxH) and template image is of size (wxh) , output image will have a size of (W-w+1, H-h+1) . Once you got the result, you can use cv2.minMaxLoc() function to find where is the maximum/minimum value. Take it as the top-left corner of rectangle and take (w,h) as width and height of the rectangle. That rectangle is your region of template.

If you are using cv2.TM_SQDIFF as comparison method, minimum value gives the best match.

Template Matching in OpenCV¶

Here, as an example, we will search for Messi’s face in his photo. So I created a template as below:

Template Image

We will try all the comparison methods so that we can see how their results look like:

import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('messi5.jpg',0) img2 = img.copy() template = cv2.imread('template.jpg',0) w, h = template.shape[::-1] # All the 6 methods for comparison in a list methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] for meth in methods: img = img2.copy() method = eval(meth) # Apply template Matching res = cv2.matchTemplate(img,template,method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) cv2.rectangle(img,top_left, bottom_right, 255, 2) plt.subplot(121),plt.imshow(res,cmap = 'gray') plt.title('Matching Result'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(img,cmap = 'gray') plt.title('Detected Point'), plt.xticks([]), plt.yticks([]) plt.suptitle(meth) plt.show() 
  • cv2.TM_CCOEFF

Template Image

  • cv2.TM_CCOEFF_NORMED

Template Image

  • cv2.TM_CCORR

Template Image

  • cv2.TM_CCORR_NORMED

Template Image

  • cv2.TM_SQDIFF

Template Image

  • cv2.TM_SQDIFF_NORMED

Template Image

You can see that the result using cv2.TM_CCORR is not good as we expected.

Template Matching with Multiple Objects¶

In the previous section, we searched image for Messi’s face, which occurs only once in the image. Suppose you are searching for an object which has multiple occurances, cv2.minMaxLoc() won’t give you all the locations. In that case, we will use thresholding. So in this example, we will use a screenshot of the famous game Mario and we will find the coins in it.

import cv2 import numpy as np from matplotlib import pyplot as plt img_rgb = cv2.imread('mario.png') img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread('mario_coin.png',0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where( res >= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) cv2.imwrite('res.png',img_rgb) 

Источник

Match template python cv2

In this chapter, you will learn

  • To find objects in an image using Template Matching
  • You will see these functions : cv.matchTemplate(), cv.minMaxLoc()

Theory

Template Matching is a method for searching and finding the location of a template image in a larger image. OpenCV comes with a function cv.matchTemplate() for this purpose. It simply slides the template image over the input image (as in 2D convolution) and compares the template and patch of input image under the template image. Several comparison methods are implemented in OpenCV. (You can check docs for more details). It returns a grayscale image, where each pixel denotes how much does the neighbourhood of that pixel match with template.

If input image is of size (WxH) and template image is of size (wxh), output image will have a size of (W-w+1, H-h+1). Once you got the result, you can use cv.minMaxLoc() function to find where is the maximum/minimum value. Take it as the top-left corner of rectangle and take (w,h) as width and height of the rectangle. That rectangle is your region of template.

Note If you are using cv.TM_SQDIFF as comparison method, minimum value gives the best match.

Template Matching in OpenCV

Here, as an example, we will search for Messi’s face in his photo. So I created a template as below:

messi_face.jpg

We will try all the comparison methods so that we can see how their results look like:

Источник

Сопоставление с шаблоном в OpenCV

Сопоставление с шаблоном — это метод, который используется в OpenCV для поиска расположения шаблона в большем изображении. 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)

Сопоставление шаблонов OpenCV

Сопоставление шаблонов с несколькими объектами

В приведенном выше примере мы искали изображение шаблона, которое встречалось только один раз в изображении. Предположим, что конкретный объект встречается несколько раз в конкретном изображении.

При этом сценарии мы будем использовать пороговое значение, потому что 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)

Сопоставление шаблонов с несколькими объектами

В приведенной выше программе мы взяли изображение популярной игры Super Mario в качестве основного изображения и изображение монеты в качестве изображения шаблона. Монеты встречаются несколько раз на основном изображении. Когда он находит монету на изображении, он рисует прямоугольник на монете.

Ограничение соответствия шаблонов

Существует несколько ограничений на сопоставление шаблонов, приведенных ниже:

  • Вычисление корреляционного изображения шаблона для изображений среднего и большого размера занимает много времени.
  • Возникновение шаблона должно сохранять ориентацию эталонного изображения.
  • Сопоставление шаблона не применяется к повернутой или масштабированной версии шаблона как изменение формы/размера/сдвига и т. д.

Источник

Оцените статью